插入排序

-

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 @ 2022-05-14 17:12  古墩古墩  Views(25)  Comments(0)    收藏  举报