跟打扑克摸牌给牌排序一样.
[2, 6, 4] --- [2, 6, 6] --- [2, 4, 6]
时间复杂度: O(n) ~ O(n^2)
空间复杂度: O(1)
稳定性: 稳定
稳定性:排序后 2 个相等键值的顺序和排序之前它们的顺序相同
void insertion_sort(int arr[], int len) { for(int i = 1; i < len; i++){ int key = arr[i]; int j = i - 1; while((j >= 0) && (key < arr[j])) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }
function insertionSort(arr) { var len = arr.length; var preIndex, current; for(var i = 1; i < len; i++){ preIndex = i - 1; current = arr[i]; while((preIndex >= 0) && (current < arr[preIndex])){ arr[preIndex+1] = arr[preIndex]; preIndex--; } arr[preIndex+1] = current; } return arr; }
引自: 十大经典排序算法 | 菜鸟教程