Question

I have the following code in a test case on jsPerf:

var arr = [0, 45, 96, 8, 69, 62, 80, 91, 89, 24, 6, 23, 49, 88, 26, 40, 87, 61, 83, 2, 60, 53, 43, 82, 67, 3, 65, 37, 42, 77, 73, 38, 9, 46, 75, 10, 63, 15, 47, 28, 79, 55, 59, 95, 11, 93, 70, 98, 25, 48, 30, 5, 72, 12, 84, 1, 29, 13, 50, 33, 19, 7, 31, 57, 32, 44, 74, 51, 35, 90, 86, 54, 4, 64, 92, 71, 22, 41, 16, 17, 27, 76, 39, 18, 99, 94, 36, 66, 85, 20, 21, 56, 34, 81, 14, 78, 68, 58, 97, 52];

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function quicksort( arr ) {
  if ( arr.length <= 1 ) 
    return arr;
  var i = 0, 
      len = arr.length, 
      less = [], 
      greater = [], 
      random = Math.floor( Math.random() * len ), 
      pivot = arr[ random ];
  arr.remove( random );
  for ( ; i < len - 1; i++ ){
    if ( arr[ i ] <= pivot )
      less.push( arr[ i ] );
    else 
      greater.push( arr[ i ] );
  }
  return quicksort( less ).concat( pivot, quicksort( greater ) );
};

If you copy that into your console and run quicksort( arr ), you'll see that it correctly returns a sorted array.

But for some reason, in this test case on jsPerf, my quicksort function seems to be returning only a single number ( as can be seen in 'Perparation Code Output' ). It also seems to be running way faster than it probably should.

Anybody ideas into what's going on would be greatly appreciated.

Was it helpful?

Solution

I think the problem is that you're calling that .remove() function on the original array, so it quickly strips it down to nothing. In other words, each initial call to the quicksort function removes an element.

When I make it create a copy of the array first, then it seems to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top