原理跟java那篇文章同樣,只是語言不一樣而已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 )