Inversions
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
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.
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 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.
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.
The cost
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.
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.
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.
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.