算法描述:
(1)将一个数据序列分成若干组,每组由若干相隔一段距离(称为增量)的元素组成,在一个组内采用直接插入排序算法进行排序。
(2)增量的初值一般为数据序列长度的一半,以后每完成一次循环增量减半,最后值为1.随着增量逐渐减小,组数也逐渐减小,组内元素个数增加,数据接近有序。
算法实现API:
package com.sortAlgorithm.sortDemo;
/**
* 希尔排序API
*/
public class ShellSort {
public static void sort(Comparable[] array) {
//根据数组array的长度,确定增长量rise的初始值
int rise = 1;
while (rise < array.length / 2) {
rise = 2 * rise + 1;
}
while (rise >= 1) {
for (int i = rise; i < array.length; i++) {
for (int j = i; j >= rise; j -= rise) {
if (greater(array[j - rise], array[j])) {
exchange(array, j - rise, j);
} else break;
}
}
rise = rise / 2;
}
}
//判断x是否大于y
private static boolean greater(Comparable x, Comparable y) {
boolean b = x.compareTo(y) > 0;
return b;
}
//数组索引i处元素和j处元素交换位置
private static void exchange(Comparable[] array, int i, int j) {
Comparable temp;
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
读者需要自行创建实现类加以实现。