Sorting Problem Definition Silly Sort Bubble Sort Selection Sort Insertion Sort 4/3/2019 CS 303 – Sorting Lecture 14
Sorting Given A sequence of records – V[i] Key - field to sort on - V[i].key ‘<=‘ - Linear Ordering Relationship (on Keys) Problem Arrange records so that Keys are non-decreasing Generalizations usually best to sort a list of pointers system should provide a facility to define ‘<=‘ we’ll use <, <=, >, >= as needed, i.e., V[i].key > V[i+1].key even better...let’s use Compare(i,j) (and CompareAndSwap(i,j)) 4/3/2019 CS 303 – Sorting Lecture 14
Silly Sorts ReallySilly(n) Repeat i rand(1,i); j rand(i+1,n) CompareAndSwap(i,j) Until Sorted O(???) Silly(n) for i 1 to n /* for each slot */ for j n downto 2 /* find correct x */ CompareAndSwap(j-1,j) O(n2) we can improve this one a bit, to get... 4/3/2019 CS 303 – Sorting Lecture 14
Bubble Sort BubbleSort(n) for i 1 to n-1 /* for each slot */ for j n downto i+1 /* find correct x */ CompareAndSwap(j-1,j) O(n2) Notice that all sorts (so far) have used CompareAndSwap, and have not taken note of the result of the Compare. They all do the same comparisons, no matter what the input data. They are “oblivious”. 4/3/2019 CS 303 – Sorting Lecture 14
Selection Sort SelectionSort(n) for i 0 to n-2 { /* 0 ... i are correct */ Best i for j i+1 to n-1 if Compare(j,Best) Best j Swap(i,Best) } or ExchangeSort(n) for j i+1 to n-1 CompareAndSwap(i,j) Which is better? [depends on architecture!] Which is oblivious? 4/3/2019 CS 303 – Sorting Lecture 14
Insertion Sort InsertionSort(n) for i 1 to n-1 { /* 0 ... i-1 are sorted (not “correct”) */ j i while CompareAndSwap(j,j-1) j j-1 } Beware! This program does not work! Why not? Demonstrate! Fix by: sentinel (use V[0], if available) add test for j >1 to inner loop (ouch!) add 1 pass of (say) BubbleSort to swap Min with V[1] 4/3/2019 CS 303 – Sorting Lecture 14