定义:基于插入排序的快速的排序算法。对于大规模乱序数组来说,插入排序很慢。因为它只会交换相邻的元素,因此元素只能一点一点地从数组的一端移动到另一端。希尔排序则是交换不相邻的元素以对数组的局部进行排序,并最终用插入排序将局部有序的数组排序。
代码:
public class Shell{
public static void sort(Comparable[] a){
int N = a.length;
int h = 1;
while(h < N/3)
h = 3*h + 1;//1, 4, 13, ..., 364, 1093,...
while(h >= 1){
for(int i = h; i < N; i++){
//将a[i]插入到a[i-h], a[i-2*h], a[i-3*h]之中
for(int j = i; j >= h && less(a[j], a[j-h]); j -= h)
exch(a, j, j-h);
}
h = h/3;
}
}
}
复杂度:
数学上尚未得出结论。
例子:
原数列:49 38 65 97 76 13 27 49 55 04
第01趟:49 13 65 97 76 38 27 49 55 04
第02趟:49 13 27 97 76 38 65 49 55 04
第03趟:49 13 27 49 76 38 65 97 55 04
第04趟:49 13 27 49 55 38 65 97 76 04
第05趟:49 13 27 49 55 04 65 97 76 38
第06趟:49 04 27 49 55 13 65 97 76 38
第07趟:49 04 27 49 13 55 65 97 76 38
第08趟:04 49 27 49 13 55 65 97 76 38
第09趟:04 27 49 49 13 55 65 97 76 38
第10趟:04 27 49 13 49 55 65 97 76 38
第11趟:04 27 13 49 49 55 65 97 76 38
第12趟:04 13 27 49 49 55 65 97 76 38
第13趟:04 13 27 49 49 55 65 76 97 38
第14趟:04 13 27 49 49 55 65 76 38 97
第15趟:04 13 27 49 49 55 65 38 76 97
第16趟:04 13 27 49 49 55 38 65 76 97
第17趟:04 13 27 49 49 38 55 65 76 97
第18趟:04 13 27 49 38 49 55 65 76 97
第19趟:04 13 27 38 49 49 55 65 76 97