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 )
作者:ghostwu, 出处:http://www.cnblogs.com/ghostwu
博客大多数文章均属原创,欢迎转载,且在文章页面明显位置给出原文连接