1 of 4

Your RightSignal

Algorithms · 2 of 131 / 3

Merge sort

The concept

Why sorting a million songs takes 20 million steps, not a trillion

Merge sort splits a list in half, sorts each half by calling itself (recursion), then merges the two sorted halves into one. A list of one item is already sorted, so that is where the splitting stops.

Take [5, 2, 8, 1]. It splits into [5, 2] and [8, 1], then into single items. Merging back up gives [2, 5] and [1, 8], and merging those gives [1, 2, 5, 8].

Comparing every item with every other takes about n² steps: a trillion for a million songs. Merge sort takes about n · log₂ n, roughly 20 million, since halving a million items reaches single items in about 20 levels.

What it’s forCounts the work merge sort does on a list of n items.

T(n) = 2·T(n/2) + n ≈ n · log₂ n

T(n)
steps to sort n items
2·T(n/2)
sorting the two halves, each by the same method
+ n
merging the halves, about one step per item
log₂ n
how many times n can be halved before reaching 1, e.g. 20 for a million

What it givesThe total cost: about n steps on each of log₂ n levels.

  1. n = 8: halving 8 → 4 → 2 → 1 gives 3 levels
  2. Each level merges all 8 items: 8 × 3 = 24 steps
  3. Comparing every pair would take about 8² = 64