说说对插入排序的理解
# 是什么
插入排序: 把数据插入有序表中


# 怎么用
function insert(arr) {
const len = arr.length;
let preIndex, current;
for (let i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr
}
const arr = [1, 19, 2, 5, 99, 23];
const res = insert(arr);
console.log(res); // [ 1, 2, 5, 19, 99, 23 ]
# 场景
时间复杂度O(n^2), 建议数据量小时使用
上次更新: 2021/12/19, 18:05:42