shell sort是insertion sort的一種,insertion sort每次只將元素移動一個位置,效率較低,shell sort采用h-sorted的方法,每次隔h個元素進行比較,這樣每次元素就會移動h個位置,提高了效率。
推薦的h為3X+1;
其實最后h為1就相當于insertion sort,但是是在前面經過h-sort的基礎上,也就是對partially sorted的數組進行insertion sort,效率更高。
public void shellSort(int[] a){
int N = a.length;
int h = 1;
while(h<N/3) h = 3*h+1;
while(h>=1){
//h-sort the array
for(int i = h;i<N;i++){
for(int j = i;j>h;j-=h){
if(a[j]<a[j-h]){
int ex = a[j];
a[j] = a[j-h];
a[j-h] = ex;
}
}
}
h = h/3;
}
}
shell sort的時間復雜度為O(N 3/2)