希尔排序(ShellSort)
简介:
是一种改进的插入排序。因为插入排序只适合数组基本有序的情况,当数组完全无序的时候,插入排序需要很长时间。希尔排序的实质是分组插入排序,又称缩小增量排序。
基本实现:
1.先将序列按照某个间隔(一般为n/2)进行拆分
2.使用插入排序对子序列进行排序
3.减小间隔继续拆分,拆分后再排序
4.若间隔为1,则对整个数组使用插入排序
例子:
使用希尔排序对含有数字9,1,5,8,3,7,4,6,2的数组进行排序,下标间隔是3,2,1。
1.现将9个数以增量为3,分为三组。第一组:9,8,4;第二组1,3,6;第三组5,7,2;
2.对每组元素进行插入排序可以得到。第一组:4,8,9;第二组1,3,6;第三组2,5,7;
3.排序后为的数组为:
4.以增量为2分为两组。第一组:4,2,3,9,7;第二组:1,8,5,6
5.插入排序后的数组为:
6.增量为1,直接进行插入排序,可以得到:
如图所示:
希尔排序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); } } }
希尔排序时间效率:
希尔排序最坏情况下是O(n^2),若n是2的幂次,则平均情形是O(n^1.5)。当space是偶数时,将其加1,则最坏情况可以改为O(n^1.5)。