在大多数情况下,插入排序算法比冒泡排序和选择排序要好。虽然算法仍然需要O(N^2)的时间,但是一般情况下,他要比冒泡排序快一倍,比选择排序还要快一些。
Java实现:
public class ArrayIns {
private long[] a;
private int nElems;
public ArrayIns(int max) {
a = new long[max];
nElems = 0;
}
public void insert(long value) {
a[nElems] = value;
nElems++;
}
public void display() {
for(int j=0; j<nElems; j++) {
System.out.print(a[j] + " ");
}
System.out.println("");
}
public void insertionSort() {//插入排序
int in, out;
for(out=1; out<nElems; out++) {
long temp = a[out];
in = out;
while(in>0 && a[in-1]>=temp) {
a[in] = a[in-1];
in--;
}
a[in] = temp;
}
}
}