Ideas
Take ascending order as an example:
- Compare from the second number forward
- If it is smaller than the previous number, continue to compare
- Insert the element in the right place
- The third number starts to compare
- And so on, proceed to the last number
The animation demonstration of ascending insertion sort is shown in the figure:
Time complexity : O(n 2 )
achieve
Existing array [7, 5, 4, 15, 3, 9, 6, 12]
, sort in ascending order:
Array.prototype.insertionSort = function() {
// 第一个数默认已经排序
// 从第二个数开始,遍历没有排序过的数
for (let i = 1; i < this.length; i++) {
// 提取当前遍历的元素
const temp = this[i];
// 从当前元素位置往前比较
let j = i;
while (j > 0) {
// 如果前一个数比提取的数
if (this[j - 1] > temp) {
// 将前一个数后移
this[j] = this[j - 1];
} else {
// 否则退出循环
break;
}
// 每比较一次,往前进一位
j--;
}
// 遍历完成后,将提取的数插入
this[j] = temp;
}
};
const arr = [7, 5, 4, 15, 3, 9, 6, 12];
arr.insertionSort();
console.log(arr);
Results of the: