希尔排序

-

const array = [10, 7, 2, 100, 5, 5, 230, 400, 1, -2, 8];
// 希尔排序
// 希尔排序是插入排序的升级版(减少排序次数)
// 把数组长度的一半作为第一个增量,这里为5
// 把数组分为5组
// [10(1), 7(2), 2(3), 100(4), 5(5), 5(1), 230(2), 400(3), 1(4), -2(5), 8(1)]
// 对每一组进行增量排序
// [5(1), 7(2), 2(3), 1(4), -2(5), 8(1), 230(2), 400(3), 100(4), 5(5), 10(1)]
// 再把增量减半,此时为2,会分为两组,如下
// [5(1), 7(2), 2(1), 1(2), -2(1), 8(2), 230(1), 400(2), 100(1), 5(2), 10(1)]
// 再对每个分组进行增量排序
// [-2(1), 1(2), 2(1), 5(2), 5(1), 7(2), 10(1), 8(2), 100(1), 400(2), 230(1)]
// 增量再减半,此时为1,对分组排序后,整个排序完成
// [-2(1), 1(1), 2(1), 5(1), 5(1), 7(1), 10(1), 8(1), 100(1), 400(1), 230(1)]
// 进行增量排序
// [-2, 1, 2, 5, 5, 7, 8, 10, 100, 230, 400]

function shellSort(arr) {
  // 第一层循环 设置增量(理解为步长:step)
  for(let step = Math.floor(arr.length / 2); step > 0; step = Math.floor(step / 2)) {
    // 第二层循环,对增量分好的序列进行插入排序
    for(let i = step; i < arr.length; i++) {
      const current = arr[i];
      let preIndex = i - step;
      while(preIndex >= 0 && arr[preIndex] > current) {
        arr[preIndex + step] = arr[preIndex];
        preIndex -= step;
      }
      arr[preIndex + step] = current;
    }
  }
  return arr;
}
console.log(shellSort(array));

 

 

 

 

-

posted @ 2022-05-15 17:05  古墩古墩  Views(26)  Comments(0)    收藏  举报