Merge sort in JavaScript
Advanced · 4 min read
Merge sort is one of the classic ways to put a list in order, and one of the clearest examples of recursion doing real work. It is fast on any input, it never scrambles items that tie, and the idea behind it fits in one sentence: split the list in half, sort each half, then merge the two sorted halves together.
In this tutorial you will write mergeSort from scratch. You will build the merge step first, because that is where the real work happens, then add the recursion around it. You need to know arrays, while loops and functions. Recursion is explained below.
The idea in plain words
Imagine two piles of exam papers, each already sorted by score. To combine them into one sorted pile, you only ever look at the top paper of each pile, take the lower one, and repeat. That is merging, and it is easy.
Merge sort turns any list into piles like that. It keeps splitting the list in half until each piece has one item. A list of one item is already sorted. Then it merges pieces back together, two at a time, until there is one sorted list again.
A function that calls itself on smaller pieces is recursive. The point where it stops splitting, a list of 0 or 1 items, is the base case.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
9 Merge sort
hardSort by splitting the array in half, sorting each half, and merging the two sorted halves. The sample is [34,7,23,32,5,62] giving [5,7,23,32,34,62].
Stuck? Three hints, smallest first
- 1. An array of 0 or 1 items is already sorted. That is the base case.
- 2. The merge step takes whichever front item is smaller, until one side runs out.
- 3. Use
<=when comparing during the merge, and the sort becomes stable.
Step 1: merge two sorted arrays
Keep a position in each array, i and j. While both have items left, push the smaller front item and move that position on:
function merge(left, right) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
out.push(left[i] <= right[j] ? left[i++] : right[j++]);
}
while (i < left.length) out.push(left[i++]);
while (j < right.length) out.push(right[j++]);
return out;
}
console.log(merge([7, 23, 34], [5, 32, 62])); // [ 5, 7, 23, 32, 34, 62 ]
left[i++] reads the item at i, then adds 1 to i. When one side runs out, the other side's leftovers are already in order, so the last two loops just copy them over.
Step 2: split and recurse
Now the sort itself. If the list is short enough, it is already sorted. Otherwise, split it, sort each half with a recursive call, and merge:
function merge(left, right) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
out.push(left[i] <= right[j] ? left[i++] : right[j++]);
}
while (i < left.length) out.push(left[i++]);
while (j < right.length) out.push(right[j++]);
return out;
}
function mergeSort(values) {
if (values.length <= 1) return values.slice();
const mid = Math.floor(values.length / 2);
const left = mergeSort(values.slice(0, mid));
const right = mergeSort(values.slice(mid));
return merge(left, right);
}
const sample = [34, 7, 23, 32, 5, 62];
console.log(mergeSort(sample)); // [ 5, 7, 23, 32, 34, 62 ]
console.log(sample); // [ 34, 7, 23, 32, 5, 62 ]
Here is how the sample splits and merges:
[34, 7, 23, 32, 5, 62]
[34, 7, 23] [32, 5, 62]
[34] [7, 23] [32] [5, 62]
[7] [23] [5] [62]
merge up: [7, 23] [5, 62]
[7, 23, 34] [5, 32, 62]
[5, 7, 23, 32, 34, 62]
The base case returns values.slice(), a copy, instead of values itself. That way the result is always a new array, and the original is never touched.
Step 3: let the caller choose the order
A compare function takes two items and returns a negative number if the first should come first, a positive number if the second should, and 0 for a tie. (a, b) => a - b sorts numbers from small to large. Adding it as a parameter with that default makes the sort work for anything:
function merge(left, right, compare) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
out.push(compare(left[i], right[j]) <= 0 ? left[i++] : right[j++]);
}
while (i < left.length) out.push(left[i++]);
while (j < right.length) out.push(right[j++]);
return out;
}
function mergeSort(values, compare = (a, b) => a - b) {
if (values.length <= 1) return values.slice();
const mid = Math.floor(values.length / 2);
return merge(mergeSort(values.slice(0, mid), compare), mergeSort(values.slice(mid), compare), compare);
}
console.log(mergeSort([34, 7, 23, 32, 5, 62], (a, b) => b - a)); // [ 62, 34, 32, 23, 7, 5 ]
const bookings = [
{ name: 'Ada', seats: 2 },
{ name: 'Bode', seats: 1 },
{ name: 'Chidi', seats: 2 },
{ name: 'Dele', seats: 1 },
];
const bySeats = mergeSort(bookings, (a, b) => a.seats - b.seats);
console.log(bySeats.map((b) => b.name)); // [ 'Bode', 'Dele', 'Ada', 'Chidi' ]
Step 4: why <= matters
Look at the bookings. Bode and Dele both have 1 seat, and Bode came first in the original list. He still comes first after sorting. A sort that keeps tied items in their original order is called stable.
That comes from <= 0 in the merge. On a tie, it takes from the left half, which holds the items that were earlier in the list. Change it to < 0 and ties take from the right instead, so equal items can swap places.
Step 5: why not just use sort()?
In real code you would use the built-in sort. But it has a famous trap. With no compare function, it compares items as text:
console.log([10, 9, 100].slice().sort()); // [ 10, 100, 9 ]
console.log([10, 9, 100].slice().sort((a, b) => a - b)); // [ 9, 10, 100 ]
As text, '100' comes before '9' because '1' comes before '9'. Always pass (a, b) => a - b for numbers.
The full solution
The panel has mergeSort and merge with a compare function, the stability check with bookings, and checks for empty, sorted, reversed and duplicate inputs. Press Run to see the output.
function mergeSort(values, compare = (a, b) => a - b) {
if (values.length <= 1) return values.slice(); // copy, so the input is safe
const mid = Math.floor(values.length / 2);
const left = mergeSort(values.slice(0, mid), compare);
const right = mergeSort(values.slice(mid), compare);
return merge(left, right, compare);
}
function merge(left, right, compare) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
// <= , not < : ties take from the LEFT, which is what makes it stable.
out.push(compare(left[i], right[j]) <= 0 ? left[i++] : right[j++]);
}
// One side is empty now; whatever is left is already in order.
while (i < left.length) out.push(left[i++]);
while (j < right.length) out.push(right[j++]);
return out;
}
const sample = [34, 7, 23, 32, 5, 62];
// Stability: equal keys must keep their original order.
const bookings = [
{ name: 'Ada', seats: 2 },
{ name: 'Bode', seats: 1 },
{ name: 'Chidi', seats: 2 },
{ name: 'Dele', seats: 1 },
];
const bySeats = mergeSort(bookings, (a, b) => a.seats - b.seats);
console.log("the sample:", mergeSort(sample));
console.log('input afterwards :', sample, '<- unchanged');
console.log('stable by seats :', bySeats.map((b) => b.name));
console.log("sort() on numbers :", [10, 9, 100].slice().sort(), '<- compares as TEXT');
Output
12 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the sample sorts", mergeSort(sample), [5, 7, 23, 32, 34, 62]);
test('the input is not modified', sample, [34, 7, 23, 32, 5, 62]);
test('an empty array', mergeSort([]), []);
test('one element', mergeSort([1]), [1]);
test('already sorted stays sorted', mergeSort([1, 2, 3]), [1, 2, 3]);
test('reversed gets fixed', mergeSort([3, 2, 1]), [1, 2, 3]);
test('duplicates are all kept', mergeSort([2, 1, 2, 1]), [1, 1, 2, 2]);
test('negatives sort correctly', mergeSort([3, -1, 0, -5]), [-5, -1, 0, 3]);
test('it agrees with a numeric sort()', mergeSort([10, 9, 100, 1]), [10, 9, 100, 1].slice().sort((a, b) => a - b));
test('and shows why sort() needs a comparator', [10, 9, 100, 1].slice().sort(), [1, 10, 100, 9]);
test('equal keys keep their original order', bySeats.map((b) => b.name), ['Bode', 'Dele', 'Ada', 'Chidi']);
test('a custom comparator can reverse it', mergeSort(sample, (a, b) => b - a), [62, 34, 32, 23, 7, 5]);
Merge sort is O(n log n) whatever the input, which quicksort cannot promise. Two details decide correctness. values.slice() in the base case means the original array is never written to — the assertion checks that. And <= 0 in the merge is what makes it stable: on a tie the left item goes first, so items that were already in a certain order stay that way. That is why sorting by seats leaves Bode before Dele. Note also that the plain sort() assertion is not a joke — with no comparator it converts to text, so 100 sorts before 9.
Common mistakes
- Forgetting the leftovers. When the first
whileloop ends, one side still has items. Without the last two loops, they are lost. - Using
<in the merge. The sort still orders items, but it is no longer stable, so ties can swap. - Sorting the original array. Return copies, so code that still uses the input isn't surprised.
Try it yourself
- Sort an array of words with
mergeSortand(a, b) => a.localeCompare(b). - Add a counter to
mergeand find how many times it runs for an array of 8 items. - Change the bookings sort to put the most seats first, keeping ties in their original order.