JavaScript Algorithms: Mergesort
Mergesort is a general purpose sorting algorithm that adopts a divide and conquer approach. It has O(n log n)
time complexity and is sometimes used internally by JavaScript with Array.prototype.sort()
.
There are three main steps:
- Divide the list into two (or more) sublists
- Sort each sublist (Conquer)
- Merge them into one list intelligently
// top-down implementation
function merge(left, right) {
let arr = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}
return arr.concat(left.slice().concat(right.slice()));
}
function mergeSort(arr) {
if (arr.length < 2) {
return arr;
}
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
const array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
mergeSort(array.slice()); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Want to improve your JavaScript? I have a list of recommended JavaScript books.