希尔排序

来源:互联网 发布:ubuntu安装deb软件命令 编辑:程序博客网 时间:2024/06/10 22:42
希尔排序是对直接插入排序的一种改进,利用了直接插入排序在数量少,有序性比较好的情况下效率高.
所以产生增量的概念,根据增量d将数组分割为几个子数组,然后对子数组进行直接插入排序,于是在增量d逐步递减的时候,数组的有序性越来越好,所以子数组越来越大的情况下,排序的效率依然很高.
public static void shellSort(int a[]) {
int i, j, d;
int temp;
for (d = a.length / 2; d > 0; d /= 2) {
for (i = d; i < a.length; i++) {
temp = a[i];
for (j = i - d; j >= d - 1; j -= d) {
if (a[j] > temp) {
a[j + d] = a[j];
} else
break;
}
a[j + d] = temp;
}
}
}
程序主要是根据增量按照规则(初始length/2 也许是前人研究出来比较理想的吧)变化,不断进行插入排序,中间其实就是插入排序,不过直接插入排序每次都是改变移动相邻的一个位置,这里是将 j和j-d进行排序,直接插入排序j的for判断条件是j>=0,这里是j>=d-1,其实是一样的,因为增量d最后会递减到1,所以保证最后全部数的排序j>=0就行了.


public static void main(String args[]) {
int a[] = { 28, 69, 41, 77, 70, 0, 1, 49, 59, 2, 30, 59, 49, 0, 74, 19, 64, 50, 20, 11, 63, 10, 75, 51, 41, 90,
56, 80, 22, 24, 10, 58, 60, 76, 10, 63, 13, 85, 13, 53, 35, 83, 59, 10, 57, 31, 32, 93, 87, 4, 16, 86,
79, 29, 71, 2, 91, 2, 42, 51, 56, 31, 4, 85, 5, 42, 97, 91, 43, 55, 41, 77, 42, 50, 68, 0, 28, 60, 28,
38, 96, 92, 9, 79, 20, 98, 34, 18, 65, 47, 28, 87, 66, 25, 13, 14, 83, 60, 21, 87 };
shellSort(a);
for (int i : a) {
System.out.print(i + ",");
}
}
0 0