将左侧序列看成一个有序序列,每次将一个数字插入该有序序列。
插入时,从有序序列最右侧开始比较,若比较的数较大,后移一位。
平均时间复杂度:O(N^2)
最差时间复杂度:O(N^2)
空间复杂度:O(1)
排序方式:In-place
稳定性:稳定
console.time('insertSort1');
var arr1 = [3, 1, 5, 4, 7, 6, 0, 2];
console.log('原数组', arr1);
var insertSort1 = arr => {
let len = arr.length;
if (len <= 1) return;
for (let i = 1; i < len; i++) {
let currentIndex = i;
for (let j = i - 1; j >= 0; j--) {
if (arr[j] > arr[currentIndex]) {
[arr[j], arr[currentIndex]] = [arr[currentIndex], arr[j]];
currentIndex = j;
} else {
break;
}
}
}
console.log('排序后数组', arr);
return arr;
};
insertSort1(arr1);
console.timeEnd('insertSort1');
console.time('insertSort2');
var arr2 = [3, 1, 5, 4, 7, 6, 0, 2];
var insertSort2 = arr => {
let len = arr.length;
if (len <= 1) return;
let prev, current;
for (let i = 1; i < len; i++) {
prev = i - 1;
current = arr[i];
while (prev >= 0 && arr[prev] > current) {
arr[prev + 1] = arr[prev];
prev--;
}
arr[prev + 1] = current;
}
console.log('排序后数组', arr);
return arr;
};
insertSort2(arr2);
console.timeEnd('insertSort2');
console.time('insertSort3');
var arr3 = [3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2];
var insertSort3 = arr => {
let len = arr.length;
if (len <= 1) return;
let prev;
for (let i = 1; i < len; i++) {
prev = i - 1;
while (prev >= 0 && arr[prev] > arr[prev + 1]) {
[arr[prev], arr[prev + 1]] = [arr[prev + 1], arr[prev]];
prev--;
}
}
console.log('排序后数组', arr);
return arr;
};
insertSort3(arr3);
console.timeEnd('insertSort3');
console.time('insertSort4');
var arr4 = [3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2,3, 1, 5, 4, 7, 6, 0, 2];
var insertSort4 = arr => {
let len = arr.length;
if (len <= 1) return;
let key, left, right, middle;
for (let i = 1; i < len; i++) {
key = arr[i];
left = 0;
right = i - 1;
while (left <= right) {
middle = Math.ceil((left + right) / 2);
if (arr[middle] > key) right = middle - 1;
else left = middle + 1;
}
for (let j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
arr[left] = key;
}
console.log('排序后数组', arr);
return arr;
};
insertSort4(arr4);
console.timeEnd('insertSort4');
参考链接:
插入排序参考1
插入排序参考2