Data Structures & Algorithms / Module 4: Searching and sorting

Topic 4.4

Merge sort

Split in two, sort each half, merge: always n log n.

10 min · intermediate

Watch: the pile is split until each paper is alone, then put back together in order. When joining, only the two front papers are compared.

RESULT TRAY7245901863275436
  • the two papers being compared
  • the lower one, moving now
  • in order
Step 1 of 16

8 exam papers with scores in no order. The goal: sort them from lowest to highest.

Merging two sorted piles is easy. Merge sort uses that trick over and over.

Merging is the easy part

Picture two piles of exam papers, each already sorted by score. To combine them, just look at the two top sheets, take the lower score, and repeat. You never need to look further down. Each sheet is touched once, so merging n sheets takes about n steps.

Split until there is nothing left to split

A list with one number in it is already sorted. Merge sort builds on that: split the list in two, split again, until every piece holds one number. Then merge pairs, level by level, back up. This is divide and conquer: break a big problem into small problems of the same shape, then combine the answers.

Code, for programmersMerge sort
function mergeSort(a) {
  if (a.length <= 1) return a;                 // base case: already sorted
  const mid = a.length >> 1;
  const left = mergeSort(a.slice(0, mid));
  const right = mergeSort(a.slice(mid));
  return merge(left, right);
}

function merge(left, right) {
  const out = [];
  let i = 0, j = 0;
  while (i < left.length && j < right.length) {
    // <= keeps equal items in their original order (a "stable" sort)
    out.push(left[i] <= right[j] ? left[i++] : right[j++]);
  }
  return out.concat(left.slice(i), right.slice(j));   // whatever is left over
}

Where n log n comes from

A list of 8 numbers is halved 3 times before the pieces hold one each (8, 4, 2, 1). That is log₂(8) = 3 levels. At every level, all 8 numbers are merged once. So the total is about 8 × 3. For a million numbers: about 20 levels × a million, or 20 million steps. Compare that with 500 billion for selection sort.

Quiz

  1. Why does merging two sorted lists take only about n steps?

  2. A list of 16 numbers. How many levels of splitting until each piece holds one?

  3. What is merge sort's main weakness compared with insertion sort?

0 of 3 answered.