简体   繁体   中英

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

I have done some research about Javascript sorting algorithms performance comparison, and found unexpected results. Bubble sort provided much better performance than others such as Shell sort, Quick sort and a native Javascript functionality. Why does this happen? Maybe I'm wrong in my performance testing method?

You can find my research results here .

Here are some algorithm implementation examples:

  /**
   * 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());
  }

That's because bubble sort is faster when you are sorting an array that is already sorted.

As you are sorting the same array over and over, it will be sorted in the first iteration in the first test, after that you are sorting an array that is already sorted.

To test the actual performance of sorting an array that is not already sorted, you have to create a new array for each sort iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM