120 likes | 130 Vues
CSCI 125 & 161 / ENGR 144 Lecture 15. Martin van Bommel. Initialization of Arrays. Dynamic initialization – inside a function for (i=0; i<Nelements; i++) array[i] = 0; Static initialization – in declaration int array[5] = {2, 4, 6, 8, 10}; Use static if done once in program
E N D
CSCI 125 & 161 / ENGR 144 Lecture 15 Martin van Bommel
Initialization of Arrays • Dynamic initialization – inside a function for (i=0; i<Nelements; i++) array[i] = 0; • Static initialization – in declaration int array[5] = {2, 4, 6, 8, 10}; • Use static if done once in program • Use dynamic if done multiple times
Implicit Static Initialization • If fewer elements given than are in array, rest are initialized to zero int array[5] = {2}; • Must initialize at least one for rest to be int list[10] = {0};
Omit Array Size • Permitted to omit array size in declaration if static initialization int array[] = {2, 4, 6, 8, 10}; • Gives an array of size 5 • Can determine number of elements in array in program sizeof array / sizeof array[0];
Sequential Search • When searching for an item in an unordered array, must check each element in sequence for (i=0; i<n; i++) { if (array[i] == value) return i; } return -1; • This leads to checking every element when the item is not found, and checking on average half of the elements to find the item
FindIntegerInArray int FindIntegerInArray( int key, int array[],int n ) { int i; for (i=0; i<n; i++) { if (key == array[i]) return (i); } return -1; }
Ordered Array • When searching for an item in an ordered array, can perform a sequential search • Better to start at the middle, determine which half should contain the value, and go to the middle of that part, and repeat • Called a binary search since only have to check log2 n items
Binary Search low = 0; high = n-1; while (low <= high) { mid = (low + high) / 2; if (value == array[mid]) return mid; if (value < array[mid]) high = mid - 1; else low = mid + 1; } return -1;
Search Efficiency Elements Sequential Binary n n / 2 log2 n 10 5 4 100 50 8 1000 500 11 1,000,000 500,000 21 1,000,000,000 500,000,000 31
Sorting • What if array is not ordered? • Can we order it? • Pseudocode: • for each position from start • find smallest element after that position • swap with element in the current position
Find Smallest Element int FindSmallestInteger(int array[], int low, int high) { int i, pos = low; for (i=low; i<=high; i++) { if (array[i] < array[pos]) pos = i; } return pos; }
Selection Sort void SortIntegerArray(int array[], int n) { int i, small; for (i = 0; i < n; i++) { small = FindSmallestInteger(array,i,n-1); SwapIntegerElements(array, i, small); } }