1 × 87 compares2 × 46 compareswhile i < m and j < n: if L[i] <= R[j]: out.append(L[i]) i += 1 else: out.append(R[j]) j += 1 inv += m - iout += L[i:] + R[j:]4 × 24 compares8 × 1no mergingcomparesinversions63815274+1
Number blocks: the items being sortedTrays: one row per level, signs give pieces × sizeA flash: an item still waiting on the left, one inversionThe items 6 3 8 1 5 2 7 4 split down four rows of trays to single items, then merge back up one hop at a time. When a merge takes an item from the right piece, the items still waiting on the left flash: each makes an inversion with it, so the counter adds that many at once. Each level costs at most n compares and there are log₂ n levels: Θ(n log n) for sorting and counting together.

Inversions

  1. 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.

Split, merge and count

The cost

What happens

;; step 1/8 · inversions
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

The card shows the loop of merge(); the whole runnable function, with sort_count, is in the lesson text. The slices a[:h] and a[h:] copy the list, which costs O(n) per level and does not change the Θ(n log n) total. Merging pieces of s and s items takes at most 2s − 1 compares: each compare places one item, and the last item needs none. This example hits that maximum on every level: 4, 6 and 7 compares.