selecting sorts/sorting details O(n 2 ) sorts are reasonable in - - PowerPoint PPT Presentation

selecting sorts sorting details
SMART_READER_LITE
LIVE PREVIEW

selecting sorts/sorting details O(n 2 ) sorts are reasonable in - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

Duke CPS 100

  • 18. 1

selecting sorts/sorting details

  • O(n2) 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
slide-2
SLIDE 2

Duke CPS 100

  • 18. 2

Partition code for quicksort

first

  • Quicksort partition in use

void quick(Vector<string> & a, int first,int last) { if (first < last) { int piv = partition(a,first,last); quick(a,first,piv-1); quick(a,piv+1,last); } }

  • loop invariant:

➤ statement true each time loop

test is evaluated

  • class invariant

➤ properties about state of class

true after certain functions have executed

?????????????? <= > ??? <= pivot > pivot pivot

first last last first last

what we want what we have invariant

piv k

slide-3
SLIDE 3

Duke CPS 100

  • 18. 3

Loop invariant practice:

  • Remove all zeroes from an array leaving order of other

elements unchanged

  • 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

2 3 7 2 3 7

slide-4
SLIDE 4

Duke CPS 100

  • 18. 4

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); } }

slide-5
SLIDE 5

Duke CPS 100

  • 18. 5

non-comparison based sorts

  • lower bound: Ω(n log n) for

comparison based sorts (like searching lower bound)

  • bucket sort/radix sort are

not-comparison based, faster asymptotically and in practice

  • sort a vector of ints, all ints

in the range 1..100, how?

  • radix: examine each digit of

numbers being sorted

1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9

23 34 56 25 44 73 42 26 10 16