The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other data structures (called "linked structures", that will be discussed later in the course, do not have this property Array elements remain in the order that the programmer puts them A very common operation is to sort the elements in an array Much research has been done on sorting, and entire books are written on the subject Main advantage of sorted arrays over unsorted arrays Efficiency of finding an element in the array Andrew M Morgan 2 1
Useful Array Functions #1 Write a function to print array contents to screen, one element per line, preceded with the index number void printarray( int iary[] cout << "Printing Array Contents" << endl; for (i = 0; i < numaryelems; i++ cout << "i: " << iary[i] << endl; Andrew M Morgan 3 Useful Array Functions #2 Write a function to fill an array of integers with random values in a given range void fillrandomarray( int min, int max, int iary[] for (i = 0; i < numaryelems; i++ //Assign current element to a random value iary[i] = rand( % (max - min + 1 + min; Andrew M Morgan 4 2
Useful Array Functions #3 Write a function to find the array index that contains the minimum value in a given range of elements of an array int findindexofmininrange( int startindex, int endindex, const int iary[] int minindex; int minval; //Start by assuming that the //first one is the min minval = iary[startindex]; minindex = startindex; //Continued, next column //Loop over others looking //for smaller values than min for (i = startindex + 1; i <= endindex; i++ if (iary[i] < minval minval = iary[i]; minindex = i; return (minindex; Andrew M Morgan 5 Support Function - Swap Write a function that swaps the contents of two integer variables Function must take two parameters by reference in order to change two values from the calling function void swapints( int &i1, int &i2 int temp; //Save the first value, since it will be //overwritten with the second value temp = i1; i1 = i2; i2 = temp; Andrew M Morgan 6 3
Selection Sort Selection Sort: One of the easiest and most common sorting algorithms Search through remaining portion of array looking for minimum value Swap the minimum value with the lowest numbered element previously unplaced Initial Unsorted Array 2 4 7 16 2 81 7 16 Array element to be swapped with minimum Array element containing minimum value 2 81 7 16 Selection Sort Algorithm 2 16 7 81 2 16 7 81 2 16 7 81 2 16 7 81 Andrew M Morgan 7 Final Sorted Array 2 16 6 81 7 102 Selection Sort Implementation Write a function to implement the selection sort algorithm on an array of integer values void selectionsort( int iary[] int minind; for (i = 0; i < numaryelems - 1; i++ //find index of min value between i and end of array minind = findindexofmininrange(i, numaryelems - 1, iary; if (minind!= i swapints(iary[i], iary[minind]; Andrew M Morgan 8 4
Selection Sort Demo Write a program to demonstrate the selection sort implementation int main( const int NUM_ELEMS = 10; int arytosort[num_elems]; //Fill up the array and print it out... fillrandomarray(30, 100, NUM_ELEMS, arytosort; printarray(num_elems, arytosort; //Now sort the array selectionsort(num_elems, arytosort; //print out the final sorted array printarray(num_elems, arytosort; return (0; Andrew M Morgan 9 Selection Sort Demo, Output Printing Array Contents i: 63 i: 93 i: 57 i: 38 i: 79 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array results of selection sort demo Andrew M Morgan 10 5
Intro To Bubble Sort Bubble sort is similar to selection sort Finding the minimum value is not required More intermediate swaps are performed initially, less later Main idea: Loop backwards over array through unsorted portion of array If the element before the current element is less, swap elements Array elements that have been sorted Algorithm Iteration Initial Array 2 4 2 4 X 2 4 X 2 4 1 4 2 13 1 81 1 81 2 13 2 13 X X 1 81 2 13 X 1 81 2 13 2 81 2 81 X X 2 19 3 81 2 19 2 19 3 81 3 81 X 2 19 3 55 4 81 2 19 3 55 5 81 Andrew M Morgan 11 Final Sorted Array Bubble Sort Implementation Write a function to implement the bubble sort algorithm void bubblesort( int iary[] int iter; for (iter = 0; iter < numaryelems; iter++ //loop backwards from end through unsorted part of array for (i = numaryelems - 1; i > iter; i-- //"bubble up" the element if it is lower than previous one if (iary[i] < iary[i - 1] swapints(iary[i], iary[i-1]; Andrew M Morgan 12 6
Bubble Sort Demo Write a program to demonstrate the bubble sort implementation int main( const int NUM_ELEMS = 10; int arytosort[num_elems]; //Fill up the array and print it out... fillrandomarray(30, 100, NUM_ELEMS, arytosort; printarray(num_elems, arytosort; //Now sort the array bubblesort(num_elems, arytosort; //print out the final sorted array printarray(num_elems, arytosort; return (0; Andrew M Morgan 13 Bubble Sort Demo, Output Printing Array Contents i: 63 i: 93 i: 57 i: 38 i: 79 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array results of bubble sort demo Andrew M Morgan 14 7
Analysis When Array Elements Are Random The following compares the two sort algorithms discussed The arrays were filled with initial values that are completely random Selection Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 24631 Total Time : 11 Num Swaps: 49259 Bubble Sort Analysis Output Total Time : 10 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 152901558 Total Time : 37 Num Swaps: 615973663 Andrew M Morgan 15 Analysis When Mostly Sorted Initially What about cases then the array is mostly in a sorted order to begin with? This analysis was done on an array that was "mostly" sorted Selection Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 17686 Bubble Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 212008 Total Time : 12 Num Swaps: 40964 Total Time : 14 Num Swaps: 187285 Total Time : 45 Num Ary Elems: 100000 Num Compares: 704982704 Num Swaps: 79172 Total Time : 57 Num Ary Elems: 100000 Num Compares: 704982704 Num Swaps: 260975 Andrew M Morgan 16 8
Analysis When Sorted Array Has New Elems The following analysis was done when a large array is sorted, except for 5 elements at the end of the array Modified Bubble Sort: Stops algorithm if array ends up being fully sorted along the way Selection Sort Analysis Total Time : 11 Num Swaps: 48466 Bubble Sort Analysis Total Time : 15 Num Swaps: 188806 Modified Bubble Sort Analysis Total Time : 0 Num Compares: 299979 Num Swaps: 188806 Andrew M Morgan 17 Implementation Of Modified Bubble Sort void newbubblesort( int iary[] int iter; bool swapnec; for (iter = 0; iter < numaryelems; iter++ swapnec = false; for (i = numaryelems - 1; i > iter; i-- if (iary[i] < iary[i - 1] swapnec = true; swapints(iary[i], iary[i-1]; if (!swapnec return; Andrew M Morgan 18 If no swaps were necessary during an iteration, then the array is known to be sorted, and processing can stop further iterations would have no effect. 9
Additional Sort Algorithms There are many other sorting algorithms Several are more efficient than the algorithms shown here More efficient algorithms generally require the use of recursion We will talk about recursion much later in the semester Uses a divide-and-conquer algorithm Breaks large problems into smaller problems that are easy and fast to solve For those who are interested: The sorting algorithms presented here are O(n 2 More efficient algorithms run in (n log 2 n Andrew M Morgan 19 return (found; Andrew M Morgan 20 Finding An Element In An Unsorted Array If an array is unsorted, element to find could be anywhere in the array Logical way to search unsorted array Loop through nodes, comparing values, until found or end is reached Also works on sorted arrays Efficiency is O(n bool linearsearch( //true if found int elem, //val to look for //ary length const int iary[],//ary to search int &index //where found bool found; found = false; for (i = 0; i < numaryelems &&!found; i++ if (iary[i] == elem found = true; index = i; 10
Finding An Element In A Sorted Array Binary Search: Able to "ignore" half the array elements each iteration Efficiency: O(log 2 n bool binarysearch( int elem, const int iary[], int &index int endind; bool found; int midind; int startind; startind = 0; endind = numaryelems; found = false; //continued next column while (startind <= endind &&!found midind = (endind + startind / 2; if (elem == iary[midind] found = true; index = midind; else if (elem > iary[midind] startind = midind + 1; else //if (elem < iary[midind] endind = midind - 1; return (found; Andrew M Morgan 21 Analysis Of Search Algorithms Analysis done by searching a 500,000 element array for a nonexistent element, 50,000 times Linear Search Total Time: 248 seconds Elements Visited Per Search: 500,000 Total Elements Visited: 25,000,000,000 Binary Search Total Time: < 1 second Elements Visited Per Search: 18 Total Elements Visited: 900,000 Analysis done by searching a 500,000 element array for the element in the second position, 50,000 times Linear Search Total Time: < 1 second Elements Visited Per Search: 3 Total Elements Visited: 150,000 Binary Search Total Time: < 1 second Elements Visited Per Search: 17 Total Elements Visited: 850,000 Andrew M Morgan 22 11