插人排序每次排一个数组项,以此方式构建最后的排序数组。假定第一项已经排序了,接着, 它和第二项进行比较,第二项是应该待在原位还是插到第一项之前呢?这样,头两项就已正确排 序,接着和第三项比较(它是该插人到第一、第二还是第三的位置呢?),以此类推。
Array.prototype.insertionSort = function() {
let j;
let temp;
for (let i = 1; i < this.length; i++) {
j = i; //2
temp = this[i]; //temp => [2]
while (j > 0 && this[j - 1] > temp) {
this[j] = this[j - 1]; //this[2] => this[1]
console.log(j);
j--;
}
this[j] = temp; //this[1] =>[2]
console.log(this.join(", "));
}
return this;
};
function insertionSort(arr) {
let len = arr.length;
for (let i = 1; i < len; i++) {
for (let j = i; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
let temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
} else {
break;
}
}
}
return arr;
}