javascript之冒泡排序

 
  Array.prototype.bubble = function () {
    var temp;
 
    //第1轮比较求第一,第二轮求第二,以此类推(i<=数组成员的个数);
    for (var i = 0; i < this.length; i++) {
      
      /*
      内部循环控制比较的次数,
      第一轮比较已经得到了最大或者最小值,
      当下一轮比较的时候最大最小值就没有必要参加比较了,
      第一轮比较length-1次 (j < length-1-i)i=0;
      第二轮比较length-2次 (j < length-1-i)i=1;
      第三轮比较length-3次 (j < length-1-i)i=2;...
      j的取值决定了比较的次数,
      */
      for (var j = 0; j < this.length - 1 - i; j++) {
        if (this[j] < this[j + 1]) {
          temp = this[j];
          this[j] = this[j + 1];
          this[j + 1] = temp;
        }
      }
    }
    return this;
  
  }
  var arr = [1, 2, 3, 4, 5];
  arr.bubble();
  console.log(arr);
原文地址:https://www.cnblogs.com/hello321/p/7814673.html