Sub topic 12
Counting Inversions During the Merge
This chapter assumes you already know the top-down merge sort from earlier chapters, the linear-time merge, and the O(n log n) analysis based on T(n) = 2T(n/2) + O(n). You should also be comfortable with recursion and Python list slicing. The aim is to show that the merge step can do more than sort. It can also measure how far a sequence is from being sorted, at no extra asymptotic cost.
What an Inversion Is
An inversion in a sequence a is a pair of positions (i, j) with i < j and a[i] > a[j]. The two elements are in the wrong order relative to each other.
The inversion count tells you how unsorted a sequence is:
| Sequence | Inversions | Why |
|---|---|---|
| `[1, 2, 3, 4, 5]` | 0 | Already sorted |
| `[2, 4, 1, 3, 5]` | 3 | Pairs (2,1), (4,1), (4,3) |
| `[5, 4, 3, 2, 1]` | 10 | Every pair is out of order: 5·4/2 |
| `[3, 3, 3]` | 0 | Equal elements are not inverted |
The count runs from 0 for a sorted list to n(n−1)/2 for a reversed one. It also equals the number of adjacent swaps that insertion sort or bubble sort performs, so it predicts how much work those algorithms do. Inversion counts come up in practice when comparing rankings. If two people rank the same n films, re-label the films by the first person's order and count inversions in the second person's list. The result is the Kendall tau distance between the two rankings.
The Brute-Force Baseline
The direct method checks every pair:
def count_inversions_brute(items):
n = len(items)
count = 0
for i in range(n):
for j in range(i + 1, n):
if items[i] > items[j]:
count += 1
return count
print(count_inversions_brute([2, 4, 1, 3, 5])) # 3This takes Θ(n²) time. For a million elements that is about 5 × 10¹¹ comparisons. The brute-force version is still useful as a reference implementation for testing the fast one.
The Key Observation
Split the sequence into a left half and a right half. Every inversion then falls into exactly one of three groups:
- Both elements are in the left half.
- Both elements are in the right half.
- One element is in the left half and the other is in the right half. These are split inversions.
Recursion handles the first two groups. The third group is where merge sort helps. Once both halves are sorted, the split inversions can be counted during the merge in linear time.
Here is why. Sorting a half rearranges elements inside that half, but it never moves an element from one half to the other. So a pair with one element on each side is a split inversion before sorting exactly when it is one after sorting. That is the case whenever the left element is larger than the right element.
Now look at the merge. Suppose the left pointer is at left[i] and the right pointer is at right[j], and right[j] < left[i], so the merge takes right[j] first. The left half is sorted, so every element from left[i] to left[-1] is at least left[i] and therefore greater than right[j]. Each of those len(left) - i elements forms an inversion with right[j]. A single subtraction counts all of them.
When the merge takes left[i] instead, left[i] <= right[j], and no new inversion involves left[i] with the remaining right elements. Those right elements are all at least right[j], so they are at least left[i] too.
The Algorithm
def sort_and_count(items):
if len(items) <= 1:
return list(items), 0
mid = len(items) // 2
left, left_inv = sort_and_count(items[:mid])
right, right_inv = sort_and_count(items[mid:])
merged = []
inversions = left_inv + right_inv
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
inversions += len(left) - i
merged.extend(left[i:])
merged.extend(right[j:])
return merged, inversions
print(sort_and_count([2, 4, 1, 3, 5])) # ([1, 2, 3, 4, 5], 3)The function returns two things: the sorted list, because the parent's merge needs sorted halves, and the inversion count. The only differences from plain merge sort are the extra return value and the one line inside the else branch.
The leftover extend calls add no inversions. If right elements remain, the left half is empty, so nothing larger sits before them. If left elements remain, every right element has already been placed and counted.
A Worked Trace
Take [2, 4, 1, 3, 5]. With mid = len // 2, it splits into [2, 4] and [1, 3, 5].
None of the subproblems contain inversions. The final merge of left = [2, 4] with right = [1, 3, 5] goes like this:
| Step | Compare | Take | `i` before | Added | Running total |
|---|---|---|---|---|---|
| 1 | 2 vs 1 | 1 (right) | 0 | 2 − 0 = 2 | 2 |
| 2 | 2 vs 3 | 2 (left) | 0 | 0 | 2 |
| 3 | 4 vs 3 | 3 (right) | 1 | 2 − 1 = 1 | 3 |
| 4 | 4 vs 5 | 4 (left) | 1 | 0 | 3 |
| 5 | (left empty) | 5 | 2 | 0 | 3 |
Step 1 counts (2,1) and (4,1) together. Step 3 counts (4,3). The total of 3 matches the brute-force result.
Correctness and Running Time
The correctness argument has the same inductive shape as the one for merge sort. Assume the recursive calls return correctly sorted halves along with their exact internal inversion counts. The three groups of inversions do not overlap and together cover every pair. The merge counts each split inversion exactly once: an inversion (x, y) with x on the left and y on the right is counted at the moment y is taken, because x is still among the left elements that remain. After that point y is never considered again.
The running time keeps the same recurrence. Each level does O(n) work for merging plus O(1) work per comparison for counting, so T(n) = 2T(n/2) + O(n) = O(n log n). The extra space is the same O(n) as merge sort.
Common Errors
- Using
<instead of<=. If the comparison isleft[i] < right[j], then on a tie the merge takes the right element first and counts the equal left elements as inversions. For[3, 3]that version reports 1 instead of 0. The<=that keeps merge sort stable is also the comparison that makes the count correct. - Adding 1 instead of
len(left) - i. This counts the number of times a right element was taken first, not the number of inversions. The result is too small whenever more than one left element remains. - Dropping the recursive counts. Starting
inversionsat 0 instead ofleft_inv + right_invcounts only the top-level split inversions. - Counting from the wrong array. The count has to come from the sorted halves during the merge, not from the original order. The argument above shows why that is safe for split inversions.
- Overflow in other languages. The count can reach n(n−1)/2, about 5 × 10¹¹ for n = 10⁶. In C, C++, or Java, a 32-bit
intoverflows, so use a 64-bitlong. Python integers do not overflow.
You can also count from the other side. When the merge takes left[i], add j, the number of right elements already placed, because each of them is smaller than left[i]. Both methods count every split inversion exactly once. Use one or the other, never both.
An In-Place Version Without Slicing
Slicing copies data at every level. The version below sorts a working copy in place and reuses one buffer, which keeps the extra space at a single O(n) array:
import random
def count_inversions(items):
a = list(items)
buf = [None] * len(a)
def rec(lo, hi):
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
inv = rec(lo, mid) + rec(mid, hi)
i, j, k = lo, mid, lo
while i < mid and j < hi:
if a[i] <= a[j]:
buf[k] = a[i]
i += 1
else:
buf[k] = a[j]
j += 1
inv += mid - i
k += 1
while i < mid:
buf[k] = a[i]
i += 1
k += 1
while j < hi:
buf[k] = a[j]
j += 1
k += 1
a[lo:hi] = buf[lo:hi]
return inv
return rec(0, len(a))
def count_inversions_brute(items):
return sum(
1
for i in range(len(items))
for j in range(i + 1, len(items))
if items[i] > items[j]
)
for _ in range(500):
data = [random.randint(0, 9) for _ in range(random.randint(0, 30))]
assert count_inversions(data) == count_inversions_brute(data), data
print("all tests passed")Here mid - i plays the role of len(left) - i, because the left run covers the index range [lo, mid). The random test uses small values on purpose so that many duplicates appear, which checks the tie handling. The recursion depth is about log₂ n, so Python's default recursion limit is not a problem even for millions of elements.
Exercise
Trace sortandcount on [3, 1, 2]. What does the final merge add, and what is the total?
Show answer
The split is [3] and [1, 2]. [1, 2] contains 0 inversions. Merging [3] with [1, 2]: taking 1 adds 1 − 0 = 1, and taking 2 adds 1 − 0 = 1. Then 3 is appended. The final merge adds 2, so the total is 2, from the pairs (3,1) and (3,2).
Exercise
A colleague changes the merge comparison to left[i] < right[j]. What does the function return for [2, 2, 1], and why is it wrong?
Show answer
It returns 3 instead of the correct 2. The split is [2] and [2, 1]. Inside [2, 1] there is 1 inversion. Merging [2] with [1, 2]: taking 1 adds 1. Next it compares 2 with 2, and the strict comparison takes the right 2 first, adding 1 more for the equal left 2. That gives 1 + 1 + 1 = 3, but equal elements are not an inversion.
Exercise
Rewrite the counting rule so the count is updated when the merge takes from the left half instead of the right. What do you add, and do you still need to handle the leftover elements?
Show answer
When left[i] is taken, add j, the number of right elements already placed, since each was smaller than left[i]. Left elements that remain after the right half runs out must also add j, which by then equals len(right), so the leftover loop for the left half needs the same update. Leftover right elements add nothing.