selecting sorts/sorting details ● O(n 2 ) sorts are reasonable in certain situations ➤ advantages/disadvantages ➤ selection sort: easy to code ➤ insertion sort: stable, fast on nearly-sorted inputs ➤ bubble sort: nearly worthless ● O(n log n) sorts are the fastest comparison-based sorts ➤ quick sort is quick, degrades in the worse case ➤ merge sort is good in the worst case, uses extra storage ➤ heap sort is good in the worst case, no extra storage ● Shell sort: in between, fast, straightforward to code 18. 1 Duke CPS 100
Partition code for quicksort Quicksort partition in use ● what we want void quick(Vector<string> & a, <= pivot > pivot int first,int last) last { first if (first < last) pivot { int piv = partition(a,first,last); what we have quick(a,first,piv-1); quick(a,piv+1,last); ?????????????? } } last first loop invariant: ● ➤ statement true each time loop invariant test is evaluated <= > ??? class invariant ● first last ➤ properties about state of class true after certain functions have k piv executed 18. 2 Duke CPS 100
Loop invariant practice: ● Remove all zeroes from an array leaving order of other elements unchanged 2 3 0 0 7 0 2 3 7 ● number of elements stored in extra variable RemoveZeroes(a,num); // a is vector above, num == 6 void RemoveZeroes(Vector<int> & list, int & numElts) // pre: numElts = # elements in list // post: numElts = # elements in list, all zeros removed 18. 3 Duke CPS 100
Mergesort ● Divide and conquer, O(n log n) algorithm ➤ divide array/list into two equal halves ➤ sort each half (recursively) ➤ merge sorted subarrays/sublists together ● merging uses extra storage (when arrays/vectors used) ➤ how much extra storage? what about linked lists? void mergesort(Vector<string> & a, int first, int last) { if (first < last) { int middle = (first + last)/2; // (last-first)/2 + first mergesort(a,first,middle); mergesort(a,middle+1,last); merge(a,first,middle,last); } } 18. 4 Duke CPS 100
non-comparison based sorts lower bound: Ω (n log n) for ● comparison based sorts (like searching lower bound) bucket sort/radix sort are ● 23 34 56 25 44 73 42 26 10 16 not-comparison based, faster asymptotically and in practice 0 1 2 3 4 5 6 7 8 9 sort a vector of ints, all ints ● in the range 1..100, how? 0 1 2 3 4 5 6 7 8 9 radix: examine each digit of ● numbers being sorted 18. 5 Duke CPS 100
Recommend
More recommend