菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
221
0

javascript算法-插入排序

原创
05/13 14:22
阅读数 53854

原理跟java那篇文章一样,只是语言不同而已

var InsertSort = function( _n ){
        this.maxSize = _n;
        this.arr = [];
        this.init = function(){
            for( var i = 0; i < this.maxSize; i++ ){
                this.arr.push( Math.floor( Math.random() * 101 ) );
            }
        };
        this.sort = function(){
            var j;
            for( var i = 1, len = this.arr.length; i < len; i++ ){
                var tmp = this.arr[i];
                j = i;
                while( tmp < this.arr[j-1] && j > 0 ) {
                    this.arr[j] = this.arr[j-1];
                    j--;
                }
                this.arr[j] = tmp;
                console.log( "第" + i + "轮,排序结果:" + this.arr );
            }
        };
    }

    var oSort = new InsertSort( 10 );
    oSort.init();
    console.log( "----------------排序前----------------" );
    console.log( oSort.arr );
    oSort.sort();
    console.log( "----------------排序后----------------" );
    console.log( oSort.arr )

 

发表评论

0/200
221 点赞
0 评论
收藏