Merge Sort — Algorithms

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…

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]

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.

Why it's always O(n log n)

Big-O says how fast an algorithm's number of steps grows as the data grows.

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

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.

What you will learn