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) {...}