ENع
←Merge sort and inversions
Lesson 29 · Greedy and divide and conquer

Merge sort's recurrence and counting inversions

14 min8 steps5 questionsAdvanced
About this lesson

An inversion is a pair of items in the wrong order. Checking every pair takes Θ(n²) work, but merge sort can count them while it sorts. Watch the list 6 3 8 1 5 2 7 4 split down to single items and merge back up: each time a merge takes an item from the right piece, every item still waiting on the left forms an inversion with it, so the count jumps by that many at once. Then read the cost off the levels: T(n) = 2T(n/2) + n, which is Θ(n log n). The Software lessons "Sorting" and "Recursion" introduce merge sort and recursive calls, the Maths lesson "Proofs and induction" covers the argument style, and "The master theorem" in this course solves recurrences like this one in general.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 29 · Interactive
01 / 08

Pairs in the wrong order

An inversion is a pair of items in the wrong order: a bigger number before a smaller one. In 6 3 8 1 5 2 7 4, the pair 6, 3 is one. Checking all 28 pairs finds 15, but that takes Θ(n²) work.

a = [6, 3, 8, 1, 5, 2, 7, 4]   n = 8
inversion: positions i < j with a[i] > a[j]
pairs to check: n(n - 1)/2 = 28
inversions (15):
  (6,3) (6,1) (6,5) (6,2) (6,4)
  (3,1) (3,2) (8,1) (8,5) (8,2)
  (8,7) (8,4) (5,2) (5,4) (7,4)
a sorted list has 0; a reversed one has n(n - 1)/2
Loading figure…
or ← →
Read the lesson step by step
  1. Pairs in the wrong order

    An inversion is a pair of items in the wrong order: a bigger number before a smaller one. In 6 3 8 1 5 2 7 4, the pair 6, 3 is one. Checking all 28 pairs finds 15, but that takes Θ(n²) work.

    a = [6, 3, 8, 1, 5, 2, 7, 4]   n = 8
    inversion: positions i < j with a[i] > a[j]
    pairs to check: n(n - 1)/2 = 28
    inversions (15):
      (6,3) (6,1) (6,5) (6,2) (6,4)
      (3,1) (3,2) (8,1) (8,5) (8,2)
      (8,7) (8,4) (5,2) (5,4) (7,4)
    a sorted list has 0; a reversed one has n(n - 1)/2
  2. Split down to single items

    Merge sort halves the list, then halves each half, until every piece holds one item. For 8 items that takes 3 levels, since log₂ 8 = 3. A single item is already sorted and has no inversions.

    sort_count(a): split at h = len(a) // 2
      level 0: 1 × 8  (pieces × size)
      level 1: 2 × 4  (pieces × size)
      level 2: 4 × 2  (pieces × size)
      level 3: 8 × 1  (pieces × size)
    levels below the top: log₂ 8 = 3
    base case: len(a) <= 1 returns (a, 0)
  3. Merge single items into pairs

    Now merge back up. Merging 6 and 3 takes one compare: 3 is smaller, so it goes first, jumping past the 6 still waiting on the left. That is one inversion. Four pairs: 4 compares, 4 inversions.

    merge(L, R) with one item each
      [6] + [3] -> [3,6]   inv 1
      [8] + [1] -> [1,8]   inv 1
      [5] + [2] -> [2,5]   inv 1
      [7] + [4] -> [4,7]   inv 1
    compares 4   inversions 4
  4. Take the smaller front item

    Merge 3 6 with 1 8: compare the two front items and take the smaller. 1 comes from the right while 3 and 6 still wait on the left. Both are bigger, so add 2: inv += m - i.

    i, j point at the front items of L and R
      [3,6] + [1,8]
        take 1 from R   waiting 3,6: +2
        take 3 from L
        take 6 from L
        take 8 from the rest
      [2,5] + [4,7]
        take 2 from L
        take 4 from R   waiting 5: +1
        take 5 from L
        take 7 from the rest
    compares 6   inversions 3
  5. Pairs across the middle

    The last merge counts pairs that straddle the middle. When 2 is taken, 3, 6, 8 still wait: +3. Then 4 (+2), 5 (+2), 7 (+1). 8 inversions, without checking the 16 cross pairs one by one.

    [1,3,6,8] + [2,4,5,7]
      take 1 from L
      take 2 from R   waiting 3,6,8: +3
      take 3 from L
      take 4 from R   waiting 6,8: +2
      take 5 from R   waiting 6,8: +2
      take 6 from L
      take 7 from R   waiting 8: +1
      take 8 from the rest
    compares 7   inversions 8
    out = [1,2,3,4,5,6,7,8]
  6. Every pair meets once

    Each pair of items meets in exactly one merge: the first piece that holds both. So every inversion is counted once, and the levels add up: 4 + 3 + 8 = 15, the same as checking all 28 pairs.

    pairs level   4
    fours level   3
    final merge   8
    total         15   (brute force: 15)
    sort_count([6, 3, 8, 1, 5, 2, 7, 4])
      -> ([1, 2, 3, 4, 5, 6, 7, 8], 15)
  7. Each level costs at most n

    A merge of m items takes at most m − 1 compares, so a whole level costs under n. Here: 4, 6 and 7 compares, each below 8. Sorting n items is two sorts of n/2 plus a merge: T(n) = 2T(n/2) + n.

    compares per level (bound: n minus the number of merges)
      into 4 × 2  4   (≤ 4)
      into 2 × 4  6   (≤ 6)
      into 1 × 8  7   (≤ 7)
      total        17
    T(1) = Θ(1),  T(n) = 2T(n/2) + Θ(n)
  8. Θ(n log n), not Θ(n²)

    There are log₂ n levels and each costs at most n, so T(n) = Θ(n log n). Counting adds one addition per item taken, so the inversion count costs Θ(n log n) as well, not the Θ(n²) of checking every pair.

    levels × cost per level = log₂ n × n
    n = 8:           3 × 8 = 24  (used 17)   pairs 28
    n = 1,000,000:   n log₂ n ≈ 19,931,569
                     pairs n(n - 1)/2 = 499,999,500,000
    counting adds O(1) per take: still Θ(n log n)

Quiz Unlocks after the last step.