代码实现:
public class Insertion {
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean less(Comparable v, Comparable m){
return v.compareTo(m) < 0;
}
@SuppressWarnings({ "unused", "rawtypes" })
private static void exch(Comparable [] a, int i, int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
@SuppressWarnings({ "unused", "rawtypes" })
private static void show(Comparable [] a){
System.out.println("排序之后:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
@SuppressWarnings("rawtypes")
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;
}
@SuppressWarnings("rawtypes")
public static void sort(Comparable [] a){
int N = a.length;
int h = 1;
while (h < N/3)
h = 3*h + 1;
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(a[j], a[j-h]); j-=h) {
exch(a, j, j-h);
}
}
h = h/3;
}
}
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
//Comparable[] a = {49,38,65,97,76,13,27,49,78,34,12,64,1,8};
Comparable[] a = {49,38};
//String [] a = {"s","o","r","t","e","x","a","m","p","l","e"};
System.out.println("排序之前:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
sort(a);
assert isSorted(a);
show(a);
}
}
排序之前:
s o r t e x a m p l e
排序之后:
a e e l m o p r s t x
算法分析:
- 平均时间复杂度:希尔排序的时间复杂度和其增量序列有关系,这涉及到数学上尚未解决的难题;不过在某些序列。
- 中复杂度可以为O(n1.3)。
- 空间复杂度:O(1) 。
- 稳定性:不稳定。