Merge sort in JavaScript
You define the comparison function like this:


function(a, b) { return a - b }



and then you use it like this:


if (f(x, y) &lt;= 0) { ... }
if (f(x, y) &gt; 0) { ... }



This is a bit tedious. It would be more intuitive like this:

function(a, b) { return a &lt;= b }


and use it like this:

if (f(x, y)) { ... }
if (!f(x, y)) { ... }


Why is it faster?

I don't know, but as @Flambino commented:


  I browsed around the V8 source code and the sort function does a lot of stuff, namely handling sorting of non-array objects, arrays with "holes", and similar cases. All of that before actually sorting anything. I have no idea what exactly is causing the slowdown, but, as mentioned, there's just a lot of stuff going on there. Their implementation is also sorting in-place, which could be a contributing factor. But I honestly haven't dug that deeply


How to make it faster?

Changing the comparison function like this:

function(a, b) { return a &lt; b }


and the bubble sort condition to use 6 instead of 8 (in if (end - start &lt; 6) { ...), together, often yielded faster result in my test runs, but not always, and I don't think that means anything.

The bottom line: I don't know...

Naming and formatting

The code would be more readable if you improved some of the names. For example renaming a and a2 to part1 and part2, respectively. Or even arr1 and arr2. It would make them look more like arrays, instantly.

This may be a matter of taste, but instead of this:


var x = a[i], y = a[i+1];
if(f(x, y) &gt; 0) {a[i] = y; a[i+1] = x;}



I would find this slightly more readable:

var x = a[i];
var y = a[i + 1];
if (f(x, y) &gt; 0) {
    a[i] = y;
    a[i + 1] = x;
}