一、基本思想
希尔排序(Shell Sort)是插入排序的一种。是针对直接插入排序算法的改进。该方法又称缩小增量排序,因DL.Shell于1959年提出而得名。
先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序;然后,取第二个增量d2<d1重复上述的分组和排序,直至所取的增量dt=1(dt<dt-l<…<d2<d1),即所有记录放在同一组中进行直接插入排序为止。
二、性能分析
平均时间复杂度 O(n^2):希尔排序的时间复杂度和其增量序列有关系,这涉及到数学上尚未解决的难题;不过在某些序列中复杂度可以为O(n1.3);
空间复杂度:O(1)
稳定性:不稳定
适合中等规模的数据排序,大数据不是最优选择。但相比同时间复杂度算法而言,效率会更高。三、图片说明
备注: 以上图片来自网络
四、算法实现
public int[] sellInsertSort(int [] a) { int d = a.length; while (true) { d = d / 2; //初次以数组长度的一半为增量 for (int x = 0; x < d; x++) { for (int i = x + d; i < a.length; i = i + d) { int temp = a[i]; int j; for (j = i - d; j >= 0 && a[j] > temp; j = j - d) { a[j + d] = a[j]; } a[j + d] = temp; } } if (d == 1) { break; } } return a; } }五、测试类
package com.albertshao.algorith.study; public class ShellInsertSort { public static void main(String[] args) { ShellInsertSort sis = new ShellInsertSort(); int[] a = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12 }; System.out.println("排序之前:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); a = sis.sellInsertSort(a); } public int[] sellInsertSort(int [] a) { int d = a.length; int index = 1; while (true) { d = d / 2; //初次以数组长度的一半为增量 for (int x = 0; x < d; x++) { for (int i = x + d; i < a.length; i = i + d) { int temp = a[i]; int j; for (j = i - d; j >= 0 && a[j] > temp; j = j - d) { a[j + d] = a[j]; } a[j + d] = temp; } } System.out.print("第" + index +"趟: (增量" + d +")"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); if (d == 1) { break; } index ++; } return a; } }
排序之前: 49 38 65 97 76 13 27 49 78 34 12 第1趟: (增量5)12 27 49 78 34 13 38 65 97 76 49 第2趟: (增量2)12 13 34 27 38 65 49 76 49 78 97 第3趟: (增量1)12 13 27 34 38 49 49 65 76 78 97