一)定义
希尔排序( shell sort )是 D .L.希尔( D.L.Shell )提出的“缩小增量”的排序方法。它的作法不是每次一个元素挨一个元素的比较。而是初期选用大跨步(增量较大)间隔比较,使记录跳跃式接近它的排序位置;然后增量缩小;最后增量为 1 ,这样记录移动次数大大减少,提高了排序效率。
二)希尔排序的实现(java)
public static void sort02(int a[]) {
double d1 = a.length;
while (true) {
d1 = Math.ceil(d1 / 2);
int d = (int) d1; //步长
for (int x = 0; x < d; x++) {//内部为一组数据的排序
//根据步长将分散的数据看出一个单独的数组,使用直接插入排序。
for (int i = x + d; i < a.length; i += d) {
int j = i;
int temp = a[j];
while (j >= d && temp < a[j - d]) {
a[j] = a[j - d];
j -= d;
}
a[j] = temp;
}
}
//步长为1运算完后,直接跳出。
if (d == 1)
break;
}
}
public static void main(String[] f) {
int[] a = new int[100000];
Random random = new Random();
for (int i = 0; i < a.length; i++) {
a[i] = random.nextInt(1000);
}
// a = new int[] { 6, 7, 51, 2, 52, 8 };
long bt = System.currentTimeMillis();
ShellSort.sort02(a);
System.out.println(System.currentTimeMillis() - bt);
// for (int a_ : a)
// System.out.println(a_);
}
希尔排序和直接插入排序的效率比较:
经过简单测试(对100000个随机整数进行排序),直接插入排序耗时约6300ms,希尔排序耗时约30ms。