# JavaScript Quicksort

Posted:

Quicksort, yet again. This time, in JavaScript!

I have been using JavaScript more frequently, and have been pleasantly surprised at how fast it is.

So, I naturally wanted some test cases of things that I always thought JavaScript was too slow for. Sorting was one of those cases.

To check it out, I wrote some quicksort functions and compared them
to `Array.sort`. Here is the unscientific comparison.

Using Engineering a Sort Function as a reference, along with textbooks, etc, I wrote the following:

1 function qsort1(xs, start, end) { 2 start = start || 0; 3 if(end === undefined) { end = xs.length;} 4 5 if(end < start + INSERT_SORT_THRESHOLD) { 6 isort(xs, start, end); 7 return xs; 8 } 9 10 var i = start - 1, 11 j = end, 12 // pidx = Math.floor(Math.random() * (end - start)) + start, 13 pivot = medianOfThree(xs[start], 14 xs[Math.floor((start + end) / 2)], 15 xs[end-1]), 16 t; 17 18 while(i < j) { 19 i += 1; 20 while(i < j && xs[i] < pivot) { 21 i += 1; 22 } 23 24 j -= 1; 25 while(i < j && pivot < xs[j]) { 26 j -= 1; 27 } 28 29 if(i < j) { 30 t = xs[i]; xs[i] = xs[j]; xs[j] = t; 31 } 32 } 33 if(xs[i] < pivot) { throw 'invariant'; } 34 35 qsort1(xs, start, i); 36 qsort1(xs, i, end); 37 return xs; 38 }

This method:

- Uses a median of three pivot strategy
- Leave the pivot in place while partitioning
- Is recursive down both halves of the partition.

Lines 18 – 32 partition the data.

Originally, I used a random pivot. That works well, but the median of three can help partition the data more evenly, leading to less work.

The pivot value is copied out to a temporary during the partitioning. In JavaScript, this isn't as big of a deal, because objects besides primitives are basically reference types anyways … so copying the pivot value in that case is more like a pointer copy.

A common case that I care about is when there are many equal values in the array. This version of quicksort does not handle that well.

The next version uses the fat partitioning described in the paper to group all of the values equal to the pivot.

1 function qsort2(xs) { 2 sort(xs, 0, xs.length); 3 return xs; 4 5 // The actual sort body. 6 function sort(xs, start, end) { 7 if(end < start + INSERT_SORT_THRESHOLD ) { 8 isort(xs, start, end); 9 return; 10 } 11 12 var i = start - 1, 13 j = end, 14 u = i, 15 v = j, 16 pivot = medianOfThree(xs[start], 17 xs[Math.floor((start + end) / 2)], 18 xs[end-1]), 19 t; 20 // Reorder the values, and maintain the indices so we have 21 // the following: 22 // 23 // begin (inclusive) | end (exclusive) | description 24 // start | u | == pivot 25 // u | i | < pivot 26 // i | v | > pivot 27 // v | end | = pivot 28 29 while(i < j) { 30 i += 1; 31 while(i < j && xs[i] < pivot) { 32 i += 1; 33 } 34 35 j -= 1; 36 while(i < j && pivot < xs[j]) { 37 j -= 1; 38 } 39 40 if(i < j) { 41 t = xs[i]; xs[i] = xs[j]; xs[j] = t; 42 /* jshint ignore:start */ 43 // We are ignoring the !. Just trying to stick 44 // with < for now... 45 if(!(xs[i] < pivot)) { 46 u += 1; 47 t = xs[i]; xs[i] = xs[u]; xs[u] = t; 48 } 49 if( !(pivot < xs[j])) { 50 v -= 1; 51 t = xs[j]; xs[j] = xs[v]; xs[v] = t; 52 } 53 /* jshint ignore:end */ 54 } 55 } 56 57 // if(xs[i] < pivot) { throw 'invariant'; } 58 59 // Now, 'flip' the sides around to bring the values equal 60 // to the pivot to the middle. 61 62 j = vecswap(xs, i, v, end); 63 i = vecswap(xs, start, u + 1, i); 64 65 // xs[i] >= pivot. 66 sort(xs, start, i); 67 sort(xs, j, end); 68 } 69 }

Lines 45 – 52 swap values equal to the pivot to the outer part of the array. At the end of the partition the pivot values are brought back together in the center.

These sort routines use the `<` operator. The `Array.sort`
routine requires a comparison operator that returns `-1`, `0`, or
`1` for less than, equal to, and greater than. The custom routines
are less general (so far!)

Here are some timing results on Chrome comparing the two sorts and the system sort. These tests are unfair and likely misleading, but they are a start.

data type | qsort1 | qsort2 | Array.sort | NumPy |
---|---|---|---|---|

random double | 0.13 | 0.15 | 1.06 | 0.11 |

sawtooth [1] | 0.09 | 0.02 | 0.04 | 0.02 |

ordered | 0.04 | 0.04 | 0.59 | 0.01 |

reversed | 0.02 | 0.03 | 0.59 | 0.02 |

shuffled | 0.21 | 0.18 | 0.68 | 0.09 |

[1] | The values in the array are 0, 1, 2, 3, 0, 1, 2, 3, … the whole way to the end of the array. |

`qsort1` and `qsort2` are far less generic than `Array.sort`,
and there are likely several errors in how I am doing this timing.
Sometimes, for example I seem to be getting GC pauses while doing the
test, but I have not confirmed what is going on yet. Overall, I am
optimistic that in these cases, JavaScript can be made to run in a
reasonable amount of time. Overall, the timing is pretty variable.
That will be worth investigating before too long.

The NumPy values are in there for comparison. I am assuming that the NumPy sort is in native code underneath, and it is far easier to time python code than to write some C++ wrappers just for a comparison.

Here is a link to the test driver that launches directly into the tests.