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)