插入排序,
arr = [5, 2, 4, 6, 1, 3]
初始化状态,默认 第一个数是排序好的,也就是说,排序从1开始
for (let i = 1; i < arr.leng; i++)
首先取出一张牌,
var tmp = arr[i]
跟之前的从后向前排序。
var j = i - 1
var arr = [5, 2, 4, 6, 1, 3]
for (let i =1; i < arr.length; i++) {
var tmp = arr[i]
var j = i -1
while (j >=0 && arr[j] > tmp) {
arr[j +1] = arr[j]
j--;
}
arr[j +1] = tmp //循环内 j -- 了
}
理解完毕
伪代码:
for i =2 to arr.length
key = arr[i]
j = i - 1
while j >0 and arr[j] > key
arr[j + 1] =arr [j]
j --
arr[j + 1] = key