I implemented this merge sort in JS and noticed that for random integer numbers it's a lot faster than the build in sort functions of all the browsers I tested (Chrome, FF, IE). Does anyone have an idea why that is? Also, is there a way to make my code even faster?
function bubbleSort(f, a, start, end) {
end--;
while(end > start) {
for(var i = start; i < end; i++) {
var x = a[i], y = a[i+1];
if(f(x, y) > 0) {a[i] = y; a[i+1] = x;}
}
end--;
}
}
function merge(f, a, start, a2, start2, mid, end) {
var i = start, i1 = start2, i2 = mid;
while(i1 < mid && i2 < end) {
if(f(a2[i1], a2[i2]) <= 0) a[i++] = a2[i1++];
else a[i++] = a2[i2++];
}
if(i1 >= mid) {
i1 = i2;
mid = end;
}
while(i1 < mid) {
a[i++] = a2[i1++];
}
};
function _mergeSort(f, a1, a2, start, end) {
var mid;
if(end - start < 2) return;
if(end - start < 8) { bubbleSort(f, a1, start, end); return; }
mid = Math.floor((start + end)/2);
_mergeSort(f, a2, a1, start, mid);
_mergeSort(f, a2, a1, mid, end);
merge(f, a1, start, a2, start, mid, end);
};
function mergeSort(f, a) {
var a2 = a.slice();
_mergeSort(f, a, a2, 0, a.length);
};
Here is some JSFiddle site to test the code http://jsfiddle.net/mxbppLu0/ In Chrome I get the biggest difference (1.4 vs. 3 seconds for 10 million numbers)