Sorting is hard, let's just divide the data in half and then merge it back together. Sounds simple enough, right?
// Merge Sort Function
function merge_sort(arr) {
if (arr.length <= 1) return arr;
var mid = Math.floor(arr.length / 2);
var left = arr.slice(0, mid);
var right = arr.slice(mid);
var result = [];
// Merge the two halves
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && (right.length > 0 && left[0] <= right[0] || right.length === 0)) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result;
}
And that's it! Now you can sort your data like a boss!
Merge Sort 201: The Even Less Impressive Sort Algorithm
Quick Sort: The Sort Algorithm for Those Who Can't Be Bothered