javascript算法-插入排序

原理跟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 )
原文地址:https://www.cnblogs.com/ghostwu/p/9286614.html