1.希尔排序
希尔排序(Shell Sort)是 DL.Shell在1959年提出的,是插入排序的一种,它是对插入排序算法的改进。
其实质是一种分组排序。把数据分成几组,然后再进行组内插入排序,不断重复这样的分组过程,直到只比较相邻元素的最后一趟排序为止。
希尔排序的增量序列的选择是一个数学难题,还没有解决。在实际运用可以结合自己数据的特点来选择合适的增量序列。本文选择的增量序列为序列 {n/2,(n/2)/2…1},这个增量序列比较简单 。
2.希尔排序动图
这个动图很形象。只截了一部分,剩下的过程可以去这里看https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html。
3.Java代码
//希尔排序
public class Shell {
public static void main(String[] args) {
int[] num = {7,6,9,3,1,5,2,4};
System.out.println("未排序的数组:"+Arrays.toString(num));
//增量序列的选择没有具体的公式,可以根据自己的数据取个合适的增量序列
for (int increment = num.length/2; increment > 0 ; increment=increment/2) {
//根据增量对数组进行分组
for (int i = increment; i < num.length; i++) {
int index = i;
//进行插入排序
//注意:index-increment值的变化
while ((index-increment)>=0&&num[index]<num[index-increment]){
int temp = num[index];
num[index] = num[index-increment];
num[index-increment] = temp;
index =index-increment;
}
}
}
System.out.println("排序后的数组:"+Arrays.toString(num));
}
}
4.参考资料
https://m.runoob.com/data-structures/shell-sort.html
https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
https://www.cnblogs.com/chengxiao/p/6104371.html