希尔排序(ShellSort)
简介:
是一种改进的插入排序。因为插入排序只适合数组基本有序的情况,当数组完全无序的时候,插入排序需要很长时间。希尔排序的实质是分组插入排序,又称缩小增量排序。
基本实现:
1.先将序列按照某个增量(一般为n/2)进行拆分
2.使用插入排序对子序列进行排序
3.缩小增量继续拆分,拆分后再排序
4.若增量为1,则对整个数组使用插入排序
例子:
使用希尔排序对含有数字9,1,5,8,3,7,4,6,2共9位的数组进行排序,增量依次为4,2,1。
1.将9个数以增量为4,分为四组。第一组:9,3,2;第二组1,7;第三组5,4;第四组8,6
2.对每组元素进行插入排序可以得到。第一组:2,3,9;第二组1,7;第三组4,5;第四组6,8;
3.以增量为2分为两组。第一组:2,4,3,5,9;第二组:1,6,7,8;
4.再次进行插入排序可得 第一组:2,3,4,5,9;第二组:1,6,7,8
5.增量为1时,有一个数组
6.直接进行插入排序,可以得到
希尔排序Java代码:
public class ShellSort {
public static <T extends Comparable<? super T>> void shellSort(T[] a,int first,int last) {
if(first>=0&&first<a.length&&last>=first&&last<=a.length) {
int n =a.length; //计算数组项数
int space = n/2; //计算间隔space
while(space>0) {
for(int begin = first;begin<first+space;begin++) {
incrementalInsertionSort(a, begin, last, space);
}
space = space/2;
}
}
}
private static <T extends Comparable<? super T>> void incrementalInsertionSort(T[] a,int first,int last,int space)
{
if(first>=0&&first<a.length&&last>=first&&last<=a.length) {
for(int unsorted =first+space;unsorted<last;unsorted=unsorted+space) {
T nextToInsert = a[unsorted]; //保存下一个未排序的元素
int index =unsorted-space; //保存前一个元素的下标
while((index>=first)&&(nextToInsert.compareTo(a[index]))<0) {
a[index+space]=a[index]; //将前一个元素后移space
index = index-space;
}
a[index+space] = nextToInsert;//插入
}
}
}
public static void main(String[] args) {
Integer[] a = {45,83,72,56,95,4,3,2,1,20,99,2};
ShellSort.shellSort(a, 0, a.length);
for(Integer integer:a) {
System.out.println(integer);
}
}
}
希尔排序时间效率:
希尔排序的时间复杂度很难证明,而且与增量的选择有关,因此只需要记住就行。使用Hibbard提出的增量时的希尔排序,最坏情形时间复杂度为O(n^3/2)。使用Sedgewich提出的增量,平均时间复杂度为O(n^7/6)。