12/06/2006 CMSC 131 Fall 2006Rance Cleaveland©2006 Univeristy of MarylandLecture 40:Selection SortLast time:1. Linear search2. Binary search3. Worst-case time complexity4. Selection sortToday:1. Project #8 assigned!2. Analyzing selection sort3. Trees and heapsCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland1Project #8 Assigned! Project due 12/11 at 11pm Project is open Start before now! Read entire assignment from beginning to end before starting to code Check out assignment now from CVS Follow the instructions exactly, as much of grading is automatedCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland2Recall from Last Time Sorting: another basic operation in computer science Our version of the problem Given: array, ordering on base type of array Compute: permutation (“reordering”) of array such that elements are in order Examples Ascending order Ordering is ≤ Array a is in ascending order if a[0] ≤ a[1] ≤ … Descending order Ordering is ≥ Array a is in descending order if a[0] ≥ a[1] ≥ …CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland3Selection Sort The selection sort idea for sorting: Think of the array as consisting of two pieces: Sorted part Unsorted part Elements in sorted part are all ordered less than the elements in unsorted part Initially: sorted part is empty, unsorted part is entire array To “grow” the sorted part: Find smallest element in unsorted part Swap it with first element in unsorted partCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland4Structure of Selection Sort ImplementationTwo auxiliary functions findMin(a, i) returns index of least element in a[i], a[i+1], … a[a.length-1] swap(a, i, j) swaps a[i], a[j] selSort(a)does following:for each i = 0 … n-2 (n = # of elements in a) Find position, j, of minimum value in a[i], …a[n-1] Swap a[i], a[j]CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland5Analyzing Selection Sort: findMinfindMin(a, i) returns index of least element in a[i], a[i+1], … a[a.length-1] Code:public static String int findMin (String[] a, int start) {String min = a[start]; // Minimum value found so farint retVal = start; // Index of minimum valuefor (int i = start+1; i < a.length; i++)if (min.compareTo(a[i]) > 0) { // New minimum!min = a[i];retVal = i;}return retVal;} Complexity analysis Initialization: two assignments For each loop iteration: One comparison Two assignments How many iterations? Depends on i: n-i-1, where n is number of elements in a Worst-case: i = 0 So O(3(n-i-1) + 2) = O(n-i) = O(n)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland6Analyzing Selection Sort: swapswap(a,i,j) swaps a[i], a[j] Code:public static void swap (String[] a, int i, int j) {String tmp = a[i];a[i] = a[j];a[j] = tmp;} Complexity analysis Three assignments So complexity is O(3) = O(1) (constant time)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland7Analyzing Selection Sort:selSortSelection sort sorts a by repeatedly finding minimum in unsorted part and swapping Code:public static void selSort (String[] a) {int minIndex;for (int i = 0; i < a.length - 1; i++) {minIndex = findMin (a, i);if (minIndex != i)swap (a, i, minIndex);}} Complexity analysis: Number of loop iteratons: n-2 Complexity of iteration i One call to findMin: O(n) One assignment One comparison One swap (O(1)) So: O((n-2) * (n+3)) = O(n2+ n - 6) = O(n2) (quadratic time)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland8Other Quadratic-Time Sorting AlgorithmsBubble sort Insertion sort (“card sorting”)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland9There Are Better Sorting Algorithms!O(n log2n) is possible We will study one such algorithm: heapsort Explaining heapsort requires some background: “Binary trees” “Heaps”CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland10Binary Trees A data structure consisting of “Nodes” “Edges” Every node has one parent(node pointing to it), except single root node, which has no parent Every node has at most two children Nodes with no children are called leaves Nodes with children are calledinternal Data may be stored in nodes‘a’‘y’ ‘J’‘3’‘c’rootleafinternal nodeedgenodeCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland11Node Levels, and Complete and Perfect Binary TreesNodes can be divided into levels based on distance (= number of edges) from root The height of a tree is the longest path from root A binary tree is complete if: Every level except the last is full In the last level, every leaf is as far to the left as possible A binary tree is perfect if every level (including the last) is full‘a’‘y’ ‘J’‘3’‘c’Level 0Level 1Level 2Height of tree is 2CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland12The Tree Quiz1. Let T be a perfect tree of height na. How many leaves does T have?2nb. How many internal nodes does T have?2n- 1c. How many total nodes does T have?2n+1- 12. Let T be a complete binary tree of height na. How many leaves does T have (give range)?2n-1to 2n, inclusiveb. How many total nodes may T have (give range)?2nto 2n+1- 1, inclusive3. Let T be a complete binary tree with n nodes. What is its height?Floor (rounding down) of log2nCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland13Heaps Assume data stored in tree nodes is ordered by ≤ A heap is: A complete binary tree such that: Every parent’s data is ≥its child(ren)’s data Fact: greatest value is stored at root!1714
View Full Document