100 likes | 602 Views
Shell Sort. Shell Sort Almost Sort. Insertion Sort revisited. InsertionSort(n) for i n-1 downto 1 CompareAndSwap(i-1,i) for i 1 to n-1 {j i; while CompareAndSwap(j,j-1) j j-1 } Consider T(n) when the input is already sorted...O(n)! Why? How about “almost sorted” input?
E N D
Shell Sort Shell Sort Almost Sort CS 303 – Shell Sort Lecture 15
Insertion Sort revisited • InsertionSort(n) • for i n-1 downto 1 CompareAndSwap(i-1,i) • for i 1 to n-1 • {j i; while CompareAndSwap(j,j-1) j j-1 } • Consider T(n) when the input is already sorted...O(n)! Why? • How about “almost sorted” input? • THM: if every input value is within k positions of their final, correct, position, then InsertionSort is O(kn) = O(n) • Check by substituting k=n, which leads to O(n2) CS 303 – Shell Sort Lecture 15
Shell Sort • ShellSort(n) • for h {decreasing sequence, ending at 1} • InsertOnSubSequence(n,h) • Idea: the preliminary, coarse sorts create an ‘almost sorted’ array, very cheaply. The final Insertion sort (with h=1) runs very fast • Details • what is the best “decreasing sequence, ending at 1”? • interleave the sub-sequence sorts, so that there is one • pass over the data (with some backing up) • O(n1.???) [look it up!] – better than O(n2), but not as good as O(n log n) CS 303 – Shell Sort Lecture 15
Shell Sort (refined) • ShellSort(n) • for h {decreasing sequence, ending at 1} • for i 2 to n • { j i • while ( (j-h) > 0) • && CompareAndSwap(j,j-h)) • j j-h • } CS 303 – Shell Sort Lecture 15
Almost Sort + Insertion Sort = Right & Fast • HybridSort(n) • AlmostSort(n) • InsertionSort(n) • Very powerful idea! • AlmostSort “conditions the input” • The only strict requirement is that it not create or destroy data • Any changes that tend to order the array will help • Is allowed to punt on difficult cases! • InsertionSort guarantees correctness, and is fast when AlmostSort does something useful CS 303 – Shell Sort Lecture 15