1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
(function (W) {
function Bubble(arr) { this.arr = arr; }
Bubble.prototype.sort = function () { var len = this.arr.length; for(var i=0;i<len;i++){ for(var j=0;j<len-i-1;j++){ if(this.less(j+1,j)){ this.exchange(j+1,j); } } } };
Bubble.prototype.less = function (m,n) { return this.arr[m]<this.arr[n]; };
Bubble.prototype.exchange = function (m,n) { var swap = this.arr[m]; this.arr[m] = this.arr[n]; this.arr[n] = swap; };
Bubble.prototype.show = function () { console.log(this.arr); };
Bubble.prototype.isSorted = function () { var len = this.arr.length; for(var i=1;i<len;i++){ if(this.less(i,i-1)){ return false; } } return true; };
W.Bubble = Bubble; })(window);
(function () { var arr = [4,5,6,0,3,5,21,7,9,0,1]; var bubble = new Bubble(arr); console.log("排序前:"+bubble.isSorted()); bubble.sort(); console.log("排序后:"+bubble.isSorted()); bubble.show(); })();
|
留言
欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。