核心:通过构建有序序列,对于未排序序列,从后向前扫描(对于单向链表则只能从前往后遍历),找到相应位置并插入。实现上通常使用in-place排序(需用到O(1)的额外空间)
性质:
#!/usr/bin/env python
def insertionSort(alist):
for i, item_i in enumerate(alist):
print alist
index = i
while index > 0 and alist[index - 1] > item_i:
alist[index] = alist[index - 1]
index -= 1
alist[index] = item_i
return alist
unsorted_list = [6, 5, 3, 1, 8, 7, 2, 4]
print(insertionSort(unsorted_list))
public class Sort {
public static void main(String[] args) {
int unsortedArray[] = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
insertionSort(unsortedArray);
System.out.println("After sort: ");
for (int item : unsortedArray) {
System.out.print(item + " ");
}
}
public static void insertionSort(int[] array) {
int len = array.length;
for (int i = 0; i < len; i++) {
int index = i, array_i = array[i];
while (index > 0 && array[index - 1] > array_i) {
array[index] = array[index - 1];
index -= 1;
}
array[index] = array_i;
/* print sort process */
for (int item : array) {
System.out.print(item + " ");
}
System.out.println();
}
}
}
实现(C++):
template<typename T>
void insertion_sort(T arr[], int len) {
int i, j;
T temp;
for (int i = 1; i < len; i++) {
temp = arr[i];
for (int j = i - 1; j >= 0 && arr[j] > temp; j--) {
a[j + 1] = a[j];
}
arr[j + 1] = temp;
}
}
核心:基于插入排序,使数组中任意间隔为h的元素都是有序的,即将全部元素分为h个区域使用插入排序。其实现可类似于插入排序但使用不同增量。更高效的原因是它权衡了子数组的规模和有序性。
实现(C++):
template<typename T>
void shell_sort(T arr[], int len) {
int gap, i, j;
T temp;
for (gap = len >> 1; gap > 0; gap >>= 1)
for (i = gap; i < len; i++) {
temp = arr[i];
for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap)
arr[j + gap] = arr[j];
arr[j + gap] = temp;
}
}