定义
希尔排序是一种基于插入排序的快速的排序算法
算法思想
- 将整个数组分成间隔为h的小段
- 在每个间隔为h的小段中使用插入排序
- 排序之初,各个子数组都很短,排序之后,各个子数组都是部分有序的,这两种情况都很适合插入排序
Java
- 源码
public class Shell {
//将a[]按升序排序
public static void sort(Comparable[] a) {
int N = a.length;
int h = 1;
while (h < N / 3) h = 3 * h + 1;// 1, 4, 13, 40, 121, 364, 1093
while (h >= 1) {
// 将数组变为h有序
for (int i = h; i < N; i++) {
// 将a[i]插入到a[i-h],a[i-2*h],a[i-3*h]...之中
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h = h / 3;
}
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
// 在单行中打印数组
public static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// 测试数组元素是否有序
public static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i - 1])) return false;
return true;
}
}
- 测试用例
public class Test {
public static void main(String[] args) {
String[] test = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"};
Shell.sort(test);
assert Shell.isSorted(test);
Shell.show(test);
}
}
- 测试结果
A E E L M O P R S T X