ShellSort

The idea of Shellsort is moving entries more than one position at a time by h-sorting the array.

h = 4
L E E A M H L E P S O L T S X R
L —— M —— P  —— T
   E  ——  H  ——  S —— S
       E  ——  L  —— O  —— X
          A  ——  E  ——  L  ——  R
.
// decrease the h until h = 1
And the idea is that each of the sorts can be implemented with only a few exchanges given that the previous ones happened.
For each new group, we will use insertion sort, as I mentioned before, the insertion sort can run linear time for partial sorted arrays.

h could be 3x+1; or Sedgewick: 1 5 19 41 109 …

Java implementation:

public class shell
{
   public static void sort(Comparable[] a)
   {
       int N = a.length;
       
       int h = 1:
       while (h < N/3) h = 3*h+1;
       while (h>=1)
       {
           for (int i = h; i < N; i++){
               for (int j=I;j>=h&&less(a[j],a[j-h]);j-=h){
                   exch(a, j ,j-h);
                }
            }
            h = h/3;
        }
     }
     private static Boolean less(Comparable v, Comparable w) {...}
     private static void exch(Comparable[] a, int I, int j) {...}
發佈了29 篇原創文章 · 獲贊 0 · 訪問量 9345
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章