220 likes | 316 Views
EECS498-006 Lecture 07. 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
E N D
EECS498-006 Lecture 07 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
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 numAryElems, int iAry[] ) { int i; cout << "Printing Array Contents" << endl; for (i = 0; i < numAryElems; i++) { cout << "i: " << iAry[i] << endl; } } Andrew M Morgan
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 numAryElems, int iAry[] ) { int i; for (i = 0; i < numAryElems; i++) { //Assign current element to a random value iAry[i] = rand() % (max - min + 1) + min; } } Andrew M Morgan
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 i; 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
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
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 Array element to be swapped with minimum Array element containing minimum value Final Sorted Array Initial Unsorted Array Selection Sort Algorithm Andrew M Morgan
Selection Sort Implementation • Write a function to implement the selection sort algorithm on an array of integer values void selectionSort( int numAryElems, int iAry[] ) { int i; 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
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
Selection Sort Demo, Output Printing Array Contents i: 81 i: 63 i: 93 i: 57 i: 38 i: 79 i: 81 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 81 i: 81 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array – results of selection sort demo Andrew M Morgan
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 X X X X X Final Sorted Array X X X Andrew M Morgan
Bubble Sort Implementation • Write a function to implement the bubble sort algorithm void bubbleSort( int numAryElems, int iAry[] ) { int i; 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
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
Bubble Sort Demo, Output Printing Array Contents i: 81 i: 63 i: 93 i: 57 i: 38 i: 79 i: 81 i: 32 i: 100 i: 86 Printing Array Contents i: 32 i: 38 i: 57 i: 63 i: 79 i: 81 i: 81 i: 86 i: 93 i: 100 Original contents of randomly fill array Sorted array – results of bubble sort demo Andrew M Morgan
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 Bubble Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 24631 Total Time : 10 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 152901558 Total Time : 11 Num Ary Elems: 50000 Num Compares: 1249975000 Num Swaps: 49259 Total Time : 37 Num Ary Elems: 50000 Num Compares: 1249975000 Num Swaps: 615973663 Andrew M Morgan
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 Bubble Sort Analysis Output Selection Sort Analysis Output Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 17686 Total Time : 3 Num Ary Elems: 25000 Num Compares: 312487500 Num Swaps: 212008 Total Time : 12 Num Ary Elems: 50000 Num Compares: 1249975000 Num Swaps: 40964 Total Time : 14 Num Ary Elems: 50000 Num Compares: 1249975000 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
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 Bubble Sort Analysis Total Time : 11 Num Ary Elems: 50000 Num Compares: 1249975000 Num Swaps: 48466 Total Time : 15 Num Ary Elems: 50000 Num Compares: 1249975000 Num Swaps: 188806 Modified Bubble Sort Analysis Total Time : 0 Num Ary Elems: 50000 Num Compares: 299979 Num Swaps: 188806 Andrew M Morgan
Implementation Of Modified Bubble Sort void newBubbleSort( int numAryElems, int iAry[] ) { int iter; int i; 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; } } 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. Andrew M Morgan
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(n2) • More efficient algorithms run in (n log2 n) Andrew M Morgan
Finding An Element In An Unsorted Array bool linearSearch( //true if found int elem, //val to look for int numAryElems, //ary length const int iAry[],//ary to search int &index //where found ) { bool found; int i; found = false; for (i = 0; i < numAryElems && !found; i++) { if (iAry[i] == elem) { found = true; index = i; } } return (found); } • 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) Andrew M Morgan
Finding An Element In A Sorted Array • Binary Search: • Able to "ignore" half the array elements each iteration • Efficiency: O(log2 n) bool binarySearch( int elem, int numAryElems, 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
Analysis Of Search Algorithms • Analysis done by searching a 500,000 element array for a non-existent element, 50,000 times • Analysis done by searching a 500,000 element array for the element in the second position, 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 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