JavaScript实践数据结构和算法——希尔排序

image.png
charu.gif

image.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>希尔排序</title>
</head>
<body>
<script>
    var CArray = function () {
        this.dataStore = [10,8,3,2,5,9,4,7,35,47,20];
        this.shellsort = shellsort;
        this.gaps = [5,3,1];
        this.swap = swap;
        this.dynamiSort = dynamiSort;
    };
    function shellsort(arr,index1,index2) {
        for(var g = 0;g<this.gaps.length;g++){
            for(var i = this.gaps[g];i<this.dataStore.length;i++){
                var temp = this.dataStore[i];
                for(var j=i;j>=this.gaps[g]&&this.dataStore[j-this.gaps[g]]>temp;j-=this.gaps[g]){
                    this.dataStore[j] = this.dataStore[j-this.gaps[g]];
                }
                this.dataStore[j] = temp;
            }
            console.log("调换后",this.dataStore);
        }
    }
    //交换数组
    function swap(arr,index1,index2) {
        var temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
    function dynamiSort() {
        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++){
                for(var j = i;j>=h && this.dataStore[j]<this.dataStore[j-h];j=j-h){
                    this.swap(this.dataStore,j,j-h);
                }
            }
            h = (h-1)/3;
        }
    }
    var mynums = new CArray();
    // mynums.shellsort();
    mynums.dynamiSort();
    console.info(mynums.dataStore);
</script>
</body>
</html>

得到结果:
image.png

==================================================================

分割线

==================================================================

博主为咯学编程:父母不同意学编程,现已断绝关系;恋人不同意学编程,现已分手;亲戚不同意学编程,现已断绝来往;老板不同意学编程,现已失业三十年。。。。。。如果此博文有帮到你欢迎打赏,金额不限。。。

发布了72 篇原创文章 · 获赞 2 · 访问量 8966

猜你喜欢

转载自blog.csdn.net/qq_36079972/article/details/100522727