JS冒泡排序

2019-12-27  本文已影响0人  王远清orz
Array.prototype.mySort = function (fn) {
      for (var i = 0; i < this.length - 1; i++) {
        var isSort = true; //假设排好序
        for (var j = 0; j < this.length - i - 1; j++) {
          if (fn(this[j], this[j + 1]) > 0) {
            isSort = false;
            var tmp = this[j];
            this[j] = this[j + 1];
            this[j + 1] = tmp;
          }
        }
        if (isSort) {
          break;
        }
      }
    }

    var arr = [1, 3, 5, 43, 22, 6];
    arr.mySort(function (a, b) {
      return a - b;
    })
    console.log(arr);
上一篇下一篇

猜你喜欢

热点阅读