1 / 5

Shell Sort

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?

germain
Download Presentation

Shell Sort

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Shell Sort Shell Sort Almost Sort CS 303 – Shell Sort Lecture 15

  2. 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

  3. 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

  4. 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

  5. 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

More Related