該算法號稱是一種衝破二次時間屏障的算法,它通過比較相距一定間隔的元素來工作,每一趟比較所用的距離隨着算法的進行而減小,直到只比較相鄰一趟的元素爲止,
由於增量一直在減小,因此這個排序也稱作縮減增量排序.
如果使用增量n,則在使用n一趟排序之後,對於第i個元素,有a[i]<=a[i+n],所有相隔n個位置的元素都是被排序的.
code:
<span style="font-size:18px;">public class TestShellSort {
public static void main(String[] args){
int[] x = {81,94,11,96,12,35,17,95,28,58,41,75,15};
shellSort(x);
for(int i: x){
System.out.print(i+ " ");
}
}
public static void shellSort(int[] a){
int j;
int index =0;
for(int gap = a.length/2;gap>0;gap/=2){
for(int i=gap;i<a.length;i++){
int tmp = a[i];
for(j=i;j>=gap&&tmp<a[j-gap];j-=gap){
a[j] = a[j-gap];
}
a[j] = tmp;
}
for(int m : a){
System.out.print(m+" ");
}
++index;
System.out.println("the increment times : " + index + " increment size : "+ gap);
}
}
}
</span>
輸出:
<span style="font-size:18px;">15 94 11 58 12 35 17 95 28 96 41 75 81 the increment times : 1 increment size : 6
15 12 11 17 41 28 58 94 35 81 95 75 96 the increment times : 2 increment size : 3
11 12 15 17 28 35 41 58 75 81 94 95 96 the increment times : 3 increment size : 1
11 12 15 17 28 35 41 58 75 81 94 95 96 </span>