为什么Javascript实现Bubble排序比其他排序算法快得多?

Dmi*_*bka 8 javascript sorting bubble-sort

我做了一些研究关于JavaScript的排序算法的性能比较,发现意想不到的效果.冒泡排序提供了比其他更好的性能,如Shell排序,快速排序和本机Javascript功能.为什么会这样?也许我的性能测试方法错了?

你可以在这里找到我的研究结果.

以下是一些算法实现示例:

  /**
   * Bubble sort(optimized)
   */
  Array.prototype.bubbleSort = function ()
  {
     var n = this.length;
     do {
        var swapped = false;
        for (var i = 1; i < n; i++ ) {
           if (this[i - 1] > this[i]) {
              var tmp = this[i-1];
              this[i-1] = this[i];
              this[i] = tmp;
              swapped = true;
           }
        }
     } while (swapped);
  }

  /**
   * Quick sort
   */
  Array.prototype.quickSort = function ()
  {
      if (this.length <= 1)
          return this;

      var pivot = this[Math.round(this.length / 2)];

      return this.filter(function (x) { return x <  pivot }).quickSort().concat(
             this.filter(function (x) { return x == pivot })).concat(
             this.filter(function (x) { return x >  pivot }).quickSort());
  }
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 13

这是因为当您对已经排序的数组进行排序时,冒泡排序会更快.

当您反复对同一数组进行排序时,它将在第一次测试的第一次迭代中进行排序,然后排序已经排序的数组.

要测试对尚未排序的数组进行排序的实际性能,必须为每个排序迭代创建一个新数组.