简单(直接)插入排序:
将每一个待排序的元素,都插入到前面已经排好序的序列中去
![](https://img.haomeiwen.com/i22082630/7ab5e412e8054822.gif)
Array.prototype.insertSort = function () {
for (let i = 1; i < this.length; i++) {
let temp = this[i];
let idx = i;
for (let j = i; j > 0; j--) {
//如果当前的数大于前面的一个数则有序跳出, 前面的默认已经有序
if (temp >= this[j - 1]) {
break;
}
// 否则当前元素往后移
this[j] = this[j-1];
// 插入的位置也前移
idx--;
}
// 当前数插入到空位
this[idx] = temp;
}
return this;
}
网友评论