高级排序算法——希尔排序(间隔为1时是插入排序)

希尔排序是插入排序的升级版,在插入排序的基础上做出了很大的改善。

 

    function CArray(numElements) {
        this.dataStore = [];
        this.numElements = numElements;
        this.prints = prints;
        this.setData = setData;
        this.gaps = [ 1750, 701, 301, 132, 57, 23, 10, 4, 1 ];
        this.swap = swap;
        this.shellsort = shellsort;
        this.shellsort1 = shellsort1;
    }
    //静态间隔序列,Ciura序列,2001年在论文中提出的比较好的间隔序列
    function setData() {
        for ( var i = 0; i < this.numElements; ++i) {
            this.dataStore[i] = Math.floor(Math.random()
                    * (this.numElements + 1));
        }
    }
    function swap(arr, index1, index2) {
        var temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
    function prints() {
        for ( var i = 0; i < this.dataStore.length; ++i) {
            document.write(this.dataStore[i] + " ");
            if (i > 0 & i % 10 == 0) {
                document.write("<br />");
            }
        }
    }
    function shellsort() {
        for ( var g = 0; g < this.gaps.length; ++g) {
            var h = this.gaps[g];
            for ( var i = h; i < this.dataStore.length; ++i) {
                var temp = this.dataStore[i];
                for ( var j = i; j >= h
                        && this.dataStore[j - h] > this.dataStore[j]; j -= h) {
                    this.dataStore[j] = this.dataStore[j - h];

                }
                this.dataStore[j] = temp;

            }
        }
    }

    function shellsort1() {
        var N = this.dataStore.length;
        var h = 1;
        while (h < N / 3) {//动态生成间隔序列
            h = 3 * h + 1;
        }
        while (h >= 1) {
            for ( var i = h; i < N; i++) {
                var temp = this.dataStore[i];
                for ( var j = i; j >= h
                        && this.dataStore[j] < this.dataStore[j - h]; j -= h) {
                    this.dataStore[j] = this.dataStore[j - h];
                }
                this.dataStore[j] = temp;
            }
            h = (h - 1) / 3;
        }
    }
    var numElements = 10000;
    var nums = new CArray(numElements);
    nums.setData();
    var start = new Date().getTime();
    nums.shellsort();
    var stop = new Date().getTime();
    var elapsed = stop - start;
    document.write(" 硬编码间隔序列的希尔排序消耗的时间为: " + elapsed + " 毫秒。 ");
    document.write("<br />");
    var start = new Date().getTime();
    nums.shellsort1();
    var stop = new Date().getTime();
    var elapsed = stop - start;
    document.write(" 硬编码间隔序列的希尔排序消耗的时间为: " + elapsed + " 毫秒。 ");

 

posted @ 2016-04-16 12:46  绯乐  阅读(616)  评论(0编辑  收藏  举报