簡體   English   中英

為什么Javascript實現Bubble排序比其他排序算法快得多?

[英]Why Javascript implementation of Bubble sort much faster than others sorting algorithms?

我做了一些研究關於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());
  }

這是因為當您對已經排序的數組進行排序時,冒泡排序會更快。

當您反復對同一數組進行排序時,它將在第一次測試的第一次迭代中進行排序,然后排序已經排序的數組。

要測試對尚未排序的數組進行排序的實際性能,必須為每個排序迭代創建一個新數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM