希尔排序(Shell Sort) 实质上是插入排序(Insertion Sort)的变种,它以一组序列为间隔进行插入排序,其具体代码如下:
import edu.princeton.cs.algs4.StdOut;
public class Shell {
public static void sort(Comparable[] a) {
int h = 1;
while (h < a.length/3) { h = h*3 + 1; }
while (h >= 1) {
for (int i = h; i < a.length; i++) {
for (int j = i; j >= h; j = j - h) {
if (less(a[j - h],a[j])) j = 0;
else exch(a, j - h, j);
}
}
h = h/3;
}
}
private static boolean less(Comparable v, Comparable w) {
if (v.compareTo(w) <= 0) return true;
else return false;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void show(Comparable[] a) {
for (Comparable item : a) {
StdOut.print(item + " ");
}
StdOut.println();
}
private static boolean isSorted(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (!less(a[i], a[i+1])) return false;
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Comparable[] a = {2, 3, 4, 1, 7, 8, 6, 5, 0, -10};
Shell.sort(a);
assert isSorted(a);
}
}
希尔排序的复杂度目前没有统一的说法,但一般认为它的复杂度低于平方级别。