CSE 326: Data Structures
Sorting by Comparison
Zasha Weinberg in lieu of Steve Wolfman
Winter Quarter 2000

Sorting by Comparison algorithms
Simple: Selection Sort
(some say Insertion Sort, or Bubble Sort)
Quick: QuickSort
Good worst case:  MergeSort, HeapSort
Can we do better?

Selection Sort idea
Find the smallest element, put it first
Find the next smallest element, put it second
Find the next smallest, put it next
etc.

Selection Sort

HeapSort: sorting with a priority queue ADT (heap)

QuickSort

QuickSort Partition

QuickSort Partition (cont’d)

QuickSort
Worst case

Dealing with Slow QuickSorts
Randomly permute input
Bad cases more common than simple probability would suggest.  So, make it truly random.
Pick pivot cleverly
“Median-of-3” rule takes Median(first, middle, last element elements).
Use MergeSort or HeapSort.

QuickSort
Average Case
Model expected # of operations
Manipulate the recurrences
Get O(n log n)
(Weiss, p. 275-279)

MergeSort

MergeSort Running Time

Could we do better?*
For any possible correct Sorting by Comparison alg
What is lowest best case time?
What is lowest worst case time?

Best case time

Worst case time
How many comparisons does it take before we can be sure of the order?
This is the minimum # of comparisons that any algorithm could do.

Decision tree to sort list A,B,C

Max depth of the decision tree
How many leaves does the tree have?
What’s the shallowest tree with a given number of leaves?

Stirling’s approximation

Eine kleine Nachmath