Sorting Algorithm Comparison

JavaScript performance comparison

Test case created by torinaki

Preparation code

<script>
  /**
   * 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);
  }
  /**
   * Shell sort
   */

  Array.prototype.shellSort = function ()
  {
      var lastKey = this.length -1,
          inc = Math.round(this.length / 2),
          temp, j, i;
      while (inc > 0) {
          for (i = inc; i <= lastKey; i++) {
              temp = this[i];
              j = i;
              while (j >= inc && this[j - inc] > temp) {
                  this[j] = this[j - inc];
                  j = j - inc;
              }
              this[j] = temp;
          }
          inc = Math.round(inc / 2.2);
      }
  }
  /**
   * 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());
  }
 
 
  /**
   * Common function
   */

  var Common = {};
  Common.randomNumber = function (min, max) {
      var argc = arguments.length;
      if (argc === 0) {
          min = 0;
          max = 2147483647;
      } else if (argc === 1) {
          throw new Error('Common.prototype.randomNumber expects exactly 2 parameters, 1 given');
      }
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  Common.arrayRandom = function (min, max, size, startIndex) {
      if (typeof(startIndex) != 'number') {
          startIndex = 0;
      }
      var arr = [], i = startIndex;
      size += startIndex;
      while (i < size) {
          arr[i] = this.randomNumber(min, max);
          i++;
      }
      return arr;
  }
 
 
  var arr = Common.arrayRandom(1, 10000, 10000);
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Bubble sort
arr.bubbleSort();
pending…
Shell sort
arr.shellSort()
pending…
Native sort
arr.sort(function(i, j){
    return i-j;
})
pending…
Quick sort
arr.quickSort();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment