The example in the previous lesson, divide and conquer, was actually merge sort. Merge sort splits the array in two, sorts each half the same way, then merges the two sorted halves. This lesson explains that merge step. It works like combining two piles of cards that are each sorted, with the smallest card on top: compare the top card of both piles, take the smaller one, then repeat. The two piles are the two halves of the array, and the top card is the front number of each half.
Split down to one, then merge
Here's what happens when merge sort sorts [38, 27, 43, 3, 9, 82, 10]:
| Step | Result |
|---|---|
| Divide | [38, 27, 43] [3, 9, 82, 10] |
| Divide | [38] [27, 43] [3, 9] [82, 10] |
| Divide | [38] [27] [43] [3] [9] [82] [10] |
| Merge | [38] [27, 43] [3, 9] [10, 82] |
| Merge | [27, 38, 43] [3, 9, 10, 82] |
| Merge | [3, 9, 10, 27, 38, 43, 82] |
mergeSort calls itself (recursion) for each half. To make the recursion stop, there's a base case: an array of 0 or 1 numbers is always sorted, so it's returned right away, without calling mergeSort again.
Here is the full code:
function mergeSort(arr) {
if (arr.length <= 1) return arr; // base case: 1 number is always sorted
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const result = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) result.push(left[i++]);
else result.push(right[j++]);
}
return [...result, ...left.slice(i), ...right.slice(j)];
}
console.log(mergeSort([38, 27, 43, 3, 9, 82, 10]));
// [3, 9, 10, 27, 38, 43, 82]
midis the middle index. For 7 numbers,Math.floor(7 / 2)gives 3.arr.slice(0, mid)takes index 0 up to just before index 3:[38, 27, 43].arr.slice(mid)takes the rest:[3, 9, 82, 10].slicemakes a new array and leaves the original unchanged.- Each half is sorted by calling
mergeSortagain, thenmergejoins the results. Both functions must give back an array withreturn.
Merge: joining two sorted lists
Both arrays being merged are already sorted. So the smallest number not yet taken is always at the front of one of the arrays. For example, when [27, 38, 43] and [3, 9, 10, 82] are merged, the first number of the result is picked from just 2 numbers (27 and 3), not from 7. In the code, i points at the front number of left that hasn't been taken yet. j does the same for right. Here are the steps:
| Compare | Take | result |
|---|---|---|
| 27 with 3 | 3 | [3] |
| 27 with 9 | 9 | [3, 9] |
| 27 with 10 | 10 | [3, 9, 10] |
| 27 with 82 | 27 | [3, 9, 10, 27] |
| 38 with 82 | 38 | [3, 9, 10, 27, 38] |
| 43 with 82 | 43 | [3, 9, 10, 27, 38, 43] |
After 43 is taken, every number in left has been taken, so the while loop stops. What's left of right, [82], is simply added to the end.
left[i++]means: takeleft[i], then add one toi, so the next comparison uses the number after it.pushputs the number taken at the end ofresult.[...result, ...left.slice(i), ...right.slice(j)]makes a new array: the items ofresult, then whatever is left ofleftandright....pours the items of an array into that new array.- When two numbers are equal,
<=takes the one fromleftfirst. The numbers inleftcame first in the original array, so equal values keep their original order. A sort that keeps the original order of equal values is called stable.
Why it's always O(n log n)
Big-O says how fast an algorithm's number of steps grows as the data grows.
- One level is one round of splitting every part in two. Halving again and again takes about log n levels: 8 numbers need 3 levels, 1,000 numbers about 10 levels.
- On each level, merging handles all n numbers once, so the work is O(n) per level.
- The total is n times log n, O(n log n): about 10,000 steps for 1,000 numbers. Bubble sort needs about 500,000 comparisons for the same data.
This count holds for any data (shuffled, reversed or nearly sorted), because merge sort always splits in the middle. But merge sort uses more memory: slice and result make new arrays. So merge sort needs extra memory of about n numbers, written O(n).
⚠️ Lost numbers, undefined, and recursion with no end
- Forgetting the leftovers. The
whileloop stops as soon as every number in one of the arrays has been taken. If the rest of the other array isn't added to the end, the biggest numbers go missing from the result. - Forgetting
return. Withoutreturn, the function gives backundefined(meaning: no value). In the exercise,.join(',')is called on the result ofmergeSort, and.join(',')onundefinedthrows an error. - No base case. Without
if (arr.length <= 1) return arr;, the recursion never stops and ends with the errorMaximum call stack size exceeded.
TL;DR: Merge sort splits the array in two, again and again, until each part holds 1 number. A part of 1 number is the base case: it's always sorted, so it's returned right away without more splitting. Then merge sort merges pairs of sorted parts. A merge compares the front numbers of two arrays, takes the smaller one, repeats, then adds whatever hasn't been taken to the end. There are log n levels (how many times every part is split in two), and each level handles n numbers, so merge sort is always O(n log n), whatever the data. Merge sort is stable: equal values keep their original order. But it needs O(n) extra memory.
⚡ Split down to one
Write:
function mergeSort(arr) {
if (arr.length <= 1) return arr; // base case: 1 number is always sorted
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
Meaning: An array of 0 or 1 numbers is always sorted, so it's returned right away. That's the base case: the condition that makes mergeSort stop calling itself. A longer array is split at the middle index (mid), each half is sorted by calling mergeSort again, then merge joins the two halves.
⚡ Merge: take the smaller front number
Write:
function merge(left, right) {
const result = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) result.push(left[i++]);
else result.push(right[j++]);
}
return [...result, ...left.slice(i), ...right.slice(j)];
}
Guess first: merge joins two sorted arrays, [27, 38, 43] and [3, 9, 10, 82]. The first number of the result is picked from how many numbers?
Just 2 (27 and 3), not 7. Both arrays are already sorted, so the smallest number left is always at the front of one of them.
Meaning: i and j point at the front numbers of left and right that haven't been taken yet. The loop moves the smaller number into result. After the loop, the leftovers of the array that isn't used up are added to the end, so no number goes missing. When two numbers are equal, <= takes the one from left, which came first in the original array. So merge sort is stable: equal values keep their original order.
⚡ Always O(n log n)
Meaning: Halving again and again until each part holds 1 number takes about log n levels (one level is one round of splitting every part). On each level, merging handles all n numbers once. So the total is O(n log n) for any data, because merge sort always splits in the middle. But it needs O(n) extra memory.