十大经典排序算法系列(四) 希尔排序 js 版

  

var arr = [ 0, 0, 1, 2, 3, 4, 5, 6, 12, 22, 123, 333, 333, 444, 555, 666, 777, 888, 999];

function shellSort(arr) {
    var arrLenght = arr.length;
    var splitNum = Math.floor(arrLenght / 2);
    var countAll = 0;
    var swapAll = 0;

    function swap(arr, n1, n2) {
        if(arr[n1] > arr[n2]){
            [arr[n1], arr[n2]] = [arr[n2], arr[n1]];
            swapAll += 1;
            return true;
        }
        return false;
    }

    function one() {
        // +6 步进比较的模式 上下
        //0 1 2 3 4  5
        //6 7 8 9 10 11
        for(let i = 0;  i < arrLenght; i++){
            swap(arr, i, i+splitNum);
            countAll += 1;
        }
    }
    one();

    function two() {
        // +2 步进比较的模式 线性
        // 0 2, 4 6, 8 10, 1 3, 5 7, 9 11
        for(let i=0; i<1; i++){
            for(let n = i;  n < arrLenght; n += 2){
                swap(arr, n, n+2);
                countAll += 1;
            }
        }
    }
    two();

    function three() {
        // 插入排序
        for(let i = 0;  i < arrLenght; i++){
            var index = i;
            while(swap(arr, index, index-1)){
                index--;
                countAll += 1;
            }
        }
    }
    three();

    console.log('swapAll: ' + swapAll);
    console.log('forLoop: ' + countAll);
    return arr;
}

console.log(shellSort(arr));

swapAll: 169
forLoop: 198
[ 999, 888, 777, 666, 555, 444, 333, 333, 123, 22, 12, 6, 5, 4, 3, 2, 1, 0, 0 ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值