插入排序:思路
1.0 从第二个数开始往前比
2.0 比它大就往后排
3.0 以此类推进行到最后一个数
如果第一数比较大就往后排
以此类推
Array.prototype.insertionSort = function() {
//第一步拿出第二个数往前比
const temp = this[1];
//第二步拿到前面所有的下标
let j = 1;
while (j > 0) {
j -= 1;
}
};
const arr = [5, 4, 3, 2, 1, ];
arr.insertionSort();
Array.prototype.insertionSort = function() {
//第一步拿出第二个数往前比
const temp = this[1];
//第二步拿到前面所有的下标
let j = 1;
while (j > 0) {
//第三步如果j-1比前面数字大则移动向j-1 如果小于则没有必要继续
if (this[j - 1] > temp) {
this[j] = this[j - 1];
} else {
brkeak;
}
j -= 1;
}
};
const arr = [5, 4, 3, 2, 1, ];
arr.insertionSort();
最终我们拿到的这个j 就是我们要插入的位置
插入排序最终 加上for循环就可以了