话不多说直接上代码
preIndex 为前一个 current为当前 所以for循环当中 i 的初始值为 1 而非0 这点要注意
const arr = [2, 4, 9, 5, 2, 3, 6, 4, 1, 5, 4, 6]
function insertSort(arr) {
let preIndex, current;
let len = arr.length
for (let i = 1; i < len; i++) {
preIndex = i - 1
current = arr[i]
while (preIndex >= 0 && arr[preIndex] > current) {
// 外部当中current保存的数值为 arr[preIndex] 的值
// 在此处不能直接修改,current 相当于一个temp
arr[preIndex + 1] = arr[preIndex]
arr[preIndex] = current
preIndex--
}
}
return arr
}
console.log(insertSort(arr));