插入排序

-

复制代码
const array = [10, 7, 2, 100, 5, 5, 230, 400, 1, -2];
// 插入排序
// 把第一个数看做一个新数组,后面的数据依次插入
// 找一个基数,用基数和新数组的数从右到左依次对比,比基数大的往右移(索引加1),直到找到比基数小的数,在它后面插入
// 基数从索引1开始,直到最后一位数

function insertionSort(arr) {
  for(let i = 1, len = arr.length; i < len; i++) {
    let current = arr[i];
    let preIndex = i - 1;
    while(preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
}
复制代码

 

-

posted @   古墩古墩  Views(21)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示