插入排序的思路
从第二个数开始往前比。
比它大就往后排。
以此类推进行到最后一个数。
时间复杂度
两个嵌套循环。
O(n^2)
const arr = [5, 4, 3, 2, 1]
function insertionSort () {
const len = arr.length
for(let i = 1; i < len; i++) {
const temp = arr[i]
let j = i
while (j > 0) {
if (arr[j - 1] > temp) {
arr[j] = arr[j - 1]
} else {
break
}
j = j -1
}
arr[j] = temp
}
}
insertionSort()
console.log(arr)
1