Lect2 Array Part2
Lect2 Array Part2
https://cse.iitkgp.ac.in/pds/semester/2006a/Array.ppt
How is an array stored?
Starting from a given memory location, the
successive array elements are allocated
space in consecutive memory locations.
Array a
x: starting address of the array in memory
k: number of bytes allocated per array element
a[i] is allocated memory location at
address x + i*k
Index Rule
An array index must evaluate to an int
between 0 and n-1 where n is the number of
elements in the array.
marks[76]
location
int *p = a ;
https://bohr.wlu.ca/cp264/notes/cp264_lecture07_array.ppt
Array operations
int readarray (int x[], int size) {
#define MAXS 100 int i;
int insert (int[], int, int, int) ; for (i=0; i<size; i++)
int reverse (int[], int) ; scanf(“%d”, &x[i]) ;
int getelement (int[], int, int) ; return size;
int readarray (int[], int) ; }
main () { int getelement (int x[], int size, int pos){
int a[MAXS]; if (pos <size) return x[pos] ;
int size; return -1;
size = readarray (a, 10) ; }
size = insert (a, size, 4, 7) ;
int insert (int x[], int size, int pos, int val){
x = getelement (a, size, 3) ;
for (k=size; k>pos; k--)
size = reverse (a, size) ;
x[k] = x[k-1] ;
} x[pos] = val ;
return size+1;
}
void reverse (int x[], int size) {
int i;
for (i=0; i< (size/2); i++)
temp = x[size-i-1] ;
x[size-1-1] = x[i] ;
x[i] = temp;
}
Selection Sort Algorithm
1. for fill = 0 to n-2 do // steps 2-6 form a pass
2. set posMin to fill
3. for next = fill+1 to n-1 do
4. if item at next < item at posMin
5. set posMin to next
6. Exchange item at posMin with one at fill
• To make room:
• Hold nextPos value in a variable
• Shuffle elements to the right until gap at right place
7 12 42 59 71 86 104 212
Looking for 89
https://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture24wdl.ppt
Binary Search Example
7 12 42 59 71 86 104 212
Looking for 89
https://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture24wdl.ppt
Binary Search Example
7 12 42 59 71 86 104 212
Looking for 89
https://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture24wdl.ppt
Binary Search Example
7 12 42 59 71 86 104 212
3 = Log(8)
https://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture24wdl.ppt
Binary Search Big-O
https://www.cc.gatech.edu/~bleahy/cs1311/cs1311lecture24wdl.ppt