一. 一般插入排序
想象一下打扑克,每次都把摸上来的牌放到正确的位置,插入排序也一样,从第二个数开始依次和第一个数比较,直到放到正确的位置为止,时间复杂度为O(N^2/4), 证明如下:
代码如下
// compare
public static boolean more(int v, int w) {
return v > w;
}
// exchange
public static void exchange(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// insertionSort Algorithm
public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; i++) { // i++
for (int j = i; j > 0; j--) {
if (more(array[j-1], array[j]))
exchange(array, j-1, j );
else
break;
}
}
}
二. 希尔插入排序
我们发现,插入排序在初始序列排好序的情况下时间复杂度为O(N),所以有没有一种算法可以改进初始序列使其无限接近与排好序的序列
希尔排序就是这个目的,这种排序通过分割的方法让初始序列无限优化,直到最后一次进行插入排序的时候,序列无限接近于排好序的状况。
代码如下
// compare
public static boolean more(int v, int w) {
return v > w;
}
// exchange
public static void exchange(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// insertionSort Algorithm
public static void shellSort(int[] array) {
int increment = 1;
while (increment < array.length / 3)
increment = 3 * increment + 1; // 3X+1 increment sequence
while (increment >= 1) {
for (int i = 1; i < array.length; i++) { // i++
for (int j = i; j >= increment; j = j - increment) {
if (more(array[j-increment], array[j]))
exchange(array, j, j - increment);
else
break;
}
}
increment = increment / 3;
}
}