希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至 1 时,整个文件恰被分成一组,算法便终止。
算法稳定性:不稳定
增量序列计算方式:ht = N / 2, h[k+1] = h[k] / 2,即{N/2, (N / 2)/2, …, 1}
代码如下:
import java.util.Arrays;
/**
* 希尔排序实现
*/
public class ShellSort {
public static void main(String[] args) {
int[] test = {5,9,8,4,7,1,2,6};
sort(test);
}
public static void sort(int[] needSort){
int count = 0;
for (int increment = needSort.length/2; increment > 0;increment = increment/2){
//构造增量序列,并按增量序列进行循环
//希尔增量是希尔排序中希尔给出的增量序列ht = N / 2, h[k+1] = h[k] / 2,即{N/2, (N / 2)/2, ..., 1}
for (int i = increment; i < needSort.length; i++) {
//按增量进行简单插入排序
int current = needSort[i];
int preId = i - increment;
while (preId > -1 && needSort[preId] > current){
needSort[preId + increment] = needSort[preId];
preId -= increment;
}
needSort[preId + increment] = current;
}
count++;
System.out.println("第" + count + "趟排序完成,其希尔增量为" + increment + ",最后排序结果为:" + Arrays.toString(needSort));
}
System.out.println("希尔排序完成!最终结果为:" + Arrays.toString(needSort));
}
}
运行结果如下所示: