希尔排序又称shell排序,它是插入排序的一种改进。又称最小增量排序。
在插入排序中,若要插入的元素很小,则需要移动数组多大多数元素,才能将元素插入正确位置。
希尔排序把数组分成几个小组,组内元素的增量是n/2,这样在组内进行插入排序时,就能大跨度地移动元素,大大减少了插入排序的移动次数。(算法优越之处)
希尔排序不稳定。
时间复杂度o(nlogn).
空间复杂度o(1)
基本思想:
1、将待排序数组按增量d=n/2分成若干组,每组记录下标相差d。
2、对每组元素进行插入排序。
3、减少d值,一般取d=d/2,重复步骤1、2.当d=1时,进行完插入排序后,结束。
图例如下:
java实现源码如下:
public class ShellSort {
public void shellSort() {
int a[] = { 1, 54, 6, 3, 78, 34, 12, 45, 56, 100 };
double d1 = a.length;
int temp = 0;
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 - d;
temp = a[i];
for (; j >= 0 && temp < a[j]; j -= d) { //插入排序
a[j + d] = a[j];
}
a[j + d] = temp;
}
}
if (d == 1)
break;
}
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void main(String[] args) {
ShellSort shellSort = new ShellSort();
shellSort.shellSort();
}
}
1
3
6
12
34
45
54
56
78
100
参考文章:
1、http://wenku.baidu.com/link?url=hxOnf1fVCAdn1wClZZDWzguCBJoRVmOGQFfYiynareEviuW4qy49LM0VL_bH1iGDmA8BHSEPLFLBpmIEUUZdqIWg5UNaqXwb2XOeEka1Bp3
2、http://www.cnblogs.com/hexiaochun/archive/2012/09/11/2679583.html