插入排序的执行过程
代码如下:
let arr = [5, 4, 3, 2, 1]
function swap(arr, index1, index2) {
var temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
}
function insertSort(arr) {
for (let i = 1; i < arr.length; i++) {
let j = i
let temp = arr[i]
while (j > 0 && arr[j - 1] > temp) {
arr[j] = arr[j - 1]
j--
}
arr[j] = temp
}
}
insertSort(arr)
console.log(arr) // [1, 2, 3, 4, 5]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22