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

分割线


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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容