向Array中添加希尔排序

希尔排序思路

我们在第 i 次时取gap = n/(2的i次方),然后将数组分为gap组(从下标0开始,每相邻的gap个元素为一组),接下来我们对每一组进行直接插入排序。

希尔排序实现

Function.prototype.method = function(name, func){
    this.prototype[name] = func;
    return this;
};

Array.method('shellSort', function(){
    var len = this.length, gap = parseInt(len/2), 
        i, j, tmp;
    while(gap > 0){
        for(i=gap; i<len; i++){
            tmp = this[i];
            j = i - gap;
            while(j>=0 && tmp < this[j]){
                this[j+gap] = this[j];
                j = j - gap;
            }
            this[j + gap] = tmp;
        }
        gap = parseInt(gap/2);

    }
    return this;
});
原文地址:https://www.cnblogs.com/JChen666/p/3358335.html