57:017, Computers in Engineering Data Structures Review of Arrays, Sorting, z Our focus thus far has mainly been on Searching control structures z An array is a data structure consisting of data items of the same type z Arrays are static data structures that stay the same size throughout the program z Dynamic data structures are also possible z Will discuss these later
Arrays Array Example z An Array is: z A collection of contiguous memory locations c[0] 12 z Same name c[1] 9 z Same type c[2] 24 c[3] -15 z Locations (elements) in the array are c[[]4] 75 c[5] 319 referenced by c[6] 335 c[7] 59 z array name c[8] 61 z position within the array Note: Array indices always start at 0 z index notation: a[0] refers to the first element of array a, a[1] refers to the second element of array a, etc.
/* Fig. 6.3: fig06_03.c initializing an array */ #include
Array Initialization int main() { z int n[ 10 ]; /* n is an array of 10 integers */ Before using arrays, we must reserve int i; /* counter */ space for all elements in the computer /* initialize elements of array n to 0 */ memory for ( i = 0; i < 10; i++ ) { z Examples n[ i ] = 0; /* set element at location i to 0 */ } ///* end for */ z int c[12]; /* Array of 12 items */ printf( "%s%13s\n", "Element", "Value" ); z int b[100]; z int x[27]; /* output contents of array n in tabular format */ for ( i = 0; i < 10; i++ ) { z Array initialization example (p. 203) printf( "%7d%13d\n", i, n[ i ] ); } /* end for */ z Initializes each element to 0 return 0; /* indicates successful termination */ } /* end main */
1 Output Produced by the Program Array Initializers
z An alternate way to initialize an array (Deitel p. 204) Element Value int n[10] = {32,27,64,9,95,14,90,70,60,37}; 0 0 z Number of initializers should equal number of array 1 0 elements 2 0 z If #initializers < #elements , all the remaining 3 0 elements are initialized to zero 4 0 z At least one element has to be initialized to zero for the rest 5 0 of the elements to be zeroed 6 0 z For example: 7 0 int n[10] = {0}; 8 0 9 0 z Arrays are NOT automatically initialized to zero. z If #initializers > #elements, ignore extra initializers.
Using Symbolic Constants to Arrays as Arguments to Specify Array Sizes Functions #include
Array Arguments--Continued Array Argument Example z Arrays are passed by reference. z Example Program 6.13 from text z Function can modify the element values of the array z Prints five elements of int array a z Unsubscripted array name is actually a pointer-- contains the starting address of the array z a and its size passed to function modifyArray z Therefore, the C function can access the elements z a is repr in te d a fter the ca ll t o sh ow th a t a is of the actual array modified by the functions z However, if individual array elements are used as z Element of a passed as argument is not arguments, they are passed by value modified z Stay tuned for more information on arrays and pointers z Call by value
2 /* array a passed by reference */ /* Passing arrays and individual array elements modifyArray(a, SIZE); to functions */ printf("The values of the modified array are:\n"); #include
/* definition of function modifyElement() */ void modifyElement(int e) { printf("Value in modifyElement is %d\n", The const type qualifier e *= 2); } z Question: How can you prevent an array from being modified by a function if it is passed in Program Output: as a parameter? Effects of ppgassing entire arra y call b y reference: z The values of the original array are: Answer: Use the type qualifier, const in the 0 1 2 3 4 array declaration: The values of the modified array are: 0 2 4 6 8 void tryToModify(const int b[] ) Effects of passing array element call by value: Value of a[3] is 6 z Will result in a run-time error if function Value in modifyElement is 12 attempts to modify the array. The value of a[3] is 6
Sorting and Searching Arrays Sorting Arrays
z Searching for information in large data z Sorting: Placing the data into some particular structures is an important part of many order computer applications z E.g. Ascending or descending order. z Searching is usually much more efficient if z Very important computing operation the data is sorted into some order. z Bubble sort - a very simple sorting algorithm z Imagine trying to look up a number in the phone z Small values “bubble” their way to the top book if the listings were not in alphabetical order z Larger values move down to the bottom of the list z Therefore, sorting is also an important problem
3 Bubble Sort A bubble sort function: /* Bubble sorts array’s values into ascending order */ z Successive pairs of elements are compared bubblesort(int a[], int size ) { z If pair is in increasing order or identical: int i, pass, hold; for (pass = 1; pass < size ; pass++) { z Leave order alone for (i = 0; i < size - 1; i++) { Note: size-1 passes z If pair is in decreasing order if (a[i] > a[i + 1]) { /* Swap elements */ Note: Each pass z Swap the order of the two elements hold = a[[];i]; steps through the z Bubble sort is OK for sorting small arrays a[i] = a[i + 1]; array comparing and a[i + 1] = hold; possibly swapping z However it is not efficient for very large arrays } // end of if each adjacent pair of elements z Several more efficient sorting algorithms exist: } //end of inner for loop } // end of outer for loop z quick sort } // end of function bubblesort z heap sort z etc.
Bubble Sort Example Bubble Sort Example First Pass: Second Pass:
24 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13
13 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 89 89 89 27 27 27 27 27 27 27 27 27 27 27 27 27 27
27 27 27 89 28 28 28 28 28 28 28 28 28 1 1 1 1
28 28 28 28 89 1 1 1 1 1 1 1 1 28 24 24 24
1 1 1 1 1 89 24 24 24 24 24 24 24 24 28 28 28 24 24 24 24 24 24 89 53 53 53 53 53 53 53 53 53 53
53 53 53 53 53 53 53 89 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 89 89 89 89 89 89 89 89 89 Everything == no swap == swap == no swap == swap below this line is finished
Bubble Sort Example Bubble Sort Example
Third Pass: Fourth Pass:
13 13 13 13 13 13 13 13 13 13 13 13 13
24 24 24 24 24 24 24 24 24 1 1 1 1 27 27 27 1 1 1 1 1 1 24 24 24 24
1 1 1 27 24 24 24 24 24 24 24 24 24
24 24 24 24 27 27 27 27 27 27 27 27 27
28 28 28 28 28 28 28 28 28 28 28 28 28 53 53 53 53 53 53 53 53 53 53 53 53 53 Everything 60 60 60 60 60 60 60 60 60 60 60 60 60 below this line is finished 89 89 89 89 89 89 89 Everything 89 89 89 89 89 89 below this line is finished == no swap == swap == no swap == swap
4 Bubble Sort Example Bubble Sort Example
Fifth Pass: Sixth Pass:
13 1 1 1 1 1 1 1 1 Note: Since nothing 1 13 13 13 13 13 13 13 13 was swapped during 24 24 24 24 24 24 24 24 24 this pass, we know that the sort is finished 24 24 24 24 24 24 24 24 24
27 27 27 27 27 27 27 27 27
Everything 28 28 28 28 28 28 28 28 28 below this 53 53 53 53 53 Everything 53 53 53 53 line is finished below this 60 60 60 60 60 line is finished 60 60 60 60 89 89 89 89 89 89 89 89 89
== no swap == swap == no swap == swap
Example—Using the Bubblesort function Bubble Sort—A slight optimization
/* Program to illustrate the bubblesort function printf( “\nArrayb[] sorted in ascending order\n" ); /* bubble sort */ This program sorts an array's values into /* output sorted array */ /* loop to control number of passes */ for ( i = 0; i < SIZE; i++ ) { ascending order using the function bubblesort() */ Not_Done = 1; #include
Searching Arrays Linear Search z Linear search vs. binary search z Compares each element of the array with z Searches an array using the search key search key z Linear search compares each array element z Search key: the value to be found with the search key until it is found (or entire array is searched without success) z WkfiWorks fine with an unor dere d arrays z Linear search works fine for small, unsorted z Becomes inefficient for large arrays, arrays especially if many searches must be performed z Binary search works best for larger, sorted arrays
5 #include
/* Binary search of an array */ #include
z Works on sorted list only int binarySearch(int array[], int key, int size);
z Eliminates half of the remaining elements in the main() { searched array after each comparison int a[SIZE], i, searchKey, result; for (i = 0; i < SIZE; i++) { z Locates the middle element of the remaining a[i] = 2 * i; portion of the array and compares to search key } printf("Enter an integer search key "); z If search key is less than the middle element then scanf("%d", &searchKey); result = binarySearch(a, searchKey, SIZE); the first half of the array is searched if (result != -1) { z Otherwise, the second half is searched printf("\n%d found in array element %d\n“, searchKey, result); n z Very fast; at most n steps, where 2 > number of elements } else { printf("\n%d not found\n", searchKey); } return 0; }
/* Performs a binary search of a sorted array. Binary Search Example index of first array element that matches key, or -1 if no match is found */ Key value being searched for is 29 int binarySearch(int b[], int key,int size) { int middle; int low = 0; int high = size -1; low 1 while (low <= high) { 13 middle = (low + high) / 2; if (key == b[middle]) { 24 return middle; 26 } middle = (low+high)/2 else if (key < b[middle]) { 27 29>27 high = middle - 1; low middle } low 29 29 middle = (low+high)/2 29 29 == 29 Success!!! else 53 53 low = middle + 1; 29<53 high } 60 60 } /* end while */ high high return -1; /* key not found */ 89 89 }
6 Binary Search Example—A failed search Efficiency of Binary Search
z Consider a sorted array with 1,000,000 Key value being searched for is 25 elements
1 1 z How many comparisons are required to
13 13 25>13 search for a given key value? 24 24 24 25 >24 Remaining Average case: list is empty z Linear search: 1,000,000/2 = 500K 26 26 26 26 25<26 so search z binary search: <= log (1,000,000) = 20 27 25<27 fails. 2 z Worst case: 29 z Linear search: 1,000,000 53 z Binary search: 20 60 89
7