Sub topic 10
Counting Inversions by Extending Merge Sort
This chapter assumes you already know merge sort from the previous chapter: how it splits, recurses, and merges two sorted lists with two pointers. It also assumes the recurrence T(n) = 2T(n/2) + O(n) and its solution, O(n log n). Here you will add one line of bookkeeping to the merge step and get an algorithm that counts how far a list is from sorted.
What an Inversion Is
An inversion in a list a is a pair of positions (i, j) with i < j and a[i] > a[j]. It is a pair of elements that appear in the wrong order relative to each other.
The list [2, 4, 1, 3, 5] has three inversions:
| Pair of positions | Values | Why it counts |
|---|---|---|
| (0, 2) | 2, 1 | 2 comes before 1 but is larger |
| (1, 2) | 4, 1 | 4 comes before 1 but is larger |
| (1, 3) | 4, 3 | 4 comes before 3 but is larger |
A sorted list has 0 inversions. A list in strictly decreasing order has the maximum: every pair is inverted, which gives n(n − 1)/2. The inversion count is a measure of how unsorted a list is, and it turns up in several places:
- Ranking comparison. If two people rank the same n movies, the number of inversions between their rankings is the Kendall tau distance, a standard similarity score used in recommendation systems and voting analysis.
- Sorting cost. Insertion sort performs exactly one swap per inversion, so the inversion count tells you its exact amount of work.
- Data quality. A nearly sorted log or sensor stream has few inversions, and the count tells you how much reordering it needs.
The Brute-Force Baseline
The direct approach checks every pair:
def count_inversions_brute(a):
n = len(a)
count = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
count += 1
return count
print(count_inversions_brute([2, 4, 1, 3, 5])) # 3This takes Θ(n²) time. For a million elements that comes to about 5 × 10¹¹ comparisons, far too many. Since the answer itself can be as large as n²/2, it may seem impossible to do better. The trick is to count inversions in batches instead of one at a time.
Dividing the Problem
Split the list at the midpoint into a left half L and a right half R. Every inversion (i, j) falls into exactly one of three groups:
- Left inversions: both positions are in
L. - Right inversions: both positions are in
R. - Split inversions:
iis inLandjis inR.
The first two groups are the same problem on smaller lists, so recursion handles them. All the new work goes into the third group. This structure matches the maximum subarray problem in the next chapter: two recursive cases plus a case that crosses the split point.
Counting split inversions naively still compares every left element with every right element, which is (n/2)² comparisons. That would make the recurrence T(n) = 2T(n/2) + Θ(n²), which solves to Θ(n²), no better than brute force. We need the crossing case in linear time.
The Key Insight: Sorted Halves Make Counting Cheap
Whether an element of L is greater than an element of R does not depend on the order of elements inside each half. Sorting L internally does not change which left elements are larger than which right elements. So the split inversion count stays the same if both halves are sorted first.
Once both halves are sorted, the merge step does the counting. Suppose the merge is comparing left[i] with right[j] and right[j] is smaller. Then right[j] is also smaller than left[i+1], left[i+2], and every other element remaining in left, because left is sorted. Each of those len(left) - i elements forms a split inversion with right[j]. A single subtraction counts them all.
If the recursion returns each half sorted along with its inversion count, the merge step can count split inversions while it builds the sorted output for the level above.
The Algorithm
import random
def sort_and_count(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, inv_left = sort_and_count(a[:mid])
right, inv_right = sort_and_count(a[mid:])
out = []
i = j = 0
split_inv = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
split_inv += len(left) - i
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out, inv_left + inv_right + split_inv
def count_inversions_brute(a):
return sum(1 for i in range(len(a))
for j in range(i + 1, len(a)) if a[i] > a[j])
print(sort_and_count([2, 4, 1, 3, 5])[1]) # 3
# Randomized check against brute force, including duplicates
for _ in range(1000):
data = [random.randint(0, 10) for _ in range(random.randint(0, 30))]
assert sort_and_count(data)[1] == count_inversions_brute(data)
print("all tests passed")The base case is a list of length 0 or 1. It is already sorted and has no inversions. When the merge loop ends, one side may still have leftover elements. Leftover left elements are larger than everything already taken from the right, but each of those pairs was counted when its right element was taken. Leftover right elements are larger than every left element. So the extend calls add no inversions.
Tracing an Example
All three inversions in this list are found by the top-level merge of left = [2, 4] and right = [1, 3, 5]:
| Step | Compare | Take | Added | Running split count |
|---|---|---|---|---|
| 1 | 2 vs 1 | 1 (right) | 2 − 0 = 2 | 2 |
| 2 | 2 vs 3 | 2 (left) | 0 | 2 |
| 3 | 4 vs 3 | 3 (right) | 2 − 1 = 1 | 3 |
| 4 | 4 vs 5 | 4 (left) | 0 | 3 |
| end | — | 5 (extend) | 0 | 3 |
Step 1 counts the inversions (2, 1) and (4, 1) together. Step 3 counts (4, 3).
Correctness and Running Time
Correctness follows by strong induction on the length n. Lengths 0 and 1 are correct trivially. For larger n, the induction hypothesis says the recursive calls return correctly sorted halves and their correct internal counts. The merge produces a sorted list, just as in merge sort. Each split inversion (x in L, y in R, x > y) is counted exactly once: at the moment y is taken. At that moment x has not yet been taken, because x > y means x cannot have been taken before y. So x is among the len(left) - i remaining elements. Pairs with x ≤ y are never counted, because y is only taken when it is strictly smaller than the current left element. The three groups do not overlap and together cover every inversion, so the sum is correct.
The merge does O(1) extra work per step, so the recurrence is unchanged: T(n) = 2T(n/2) + O(n) = O(n log n). The memory use matches merge sort, O(n) auxiliary space plus O(log n) recursion depth.
Common Errors
- Adding
len(left)instead oflen(left) - i. This counts left elements that were already placed in the output. - Counting when taking from the left. You can count correctly this way by adding
j(the number of right elements already taken) each time a left element is taken. Mixing the two styles double-counts. - Returning only the count. The parent call needs the sorted half. Without it the linear-time counting argument fails.
- Sorting the halves with a library sort and counting afterward. The answer is still correct, but this adds a log factor to each level and gives O(n log² n).
Exercises
Exercise
What is the largest number of inversions a list of n distinct elements can have, and which list achieves it?
Show answer
n(n − 1)/2, achieved by the list sorted in strictly decreasing order, where every one of the n(n − 1)/2 pairs is inverted.
Exercise
The list [3, 1, 2, 3] has 2 inversions: (3, 1) and (3, 2). If the merge comparison is changed from left[i] <= right[j] to left[i] < right[j], what count does sortandcount return, and why?
Show answer
It returns 3. In the top-level merge of [1, 3] and [2, 3], the final comparison is 3 vs 3. With < the right-hand 3 is taken first and the remaining left 3 is counted as an inversion, even though equal elements are not inverted.
Exercise
Rewrite the merge loop so it counts split inversions when an element is taken from the left half instead of the right. What do you add?
Show answer
When taking left[i], add j, the number of right elements already placed in the output. Each of those is smaller than left[i] and comes after it in the original list. Leftover left elements copied by extend must also add len(right) each, because all right elements were smaller. Equivalently, add j for every left element, including the ones copied at the end.
Exercise
Two users rank the same five films. User A's order is [F1, F2, F3, F4, F5] and user B's is [F2, F4, F1, F3, F5]. How do you compute their Kendall tau distance with sortandcount, and what is it?
Show answer
Replace each film in B's list with its position in A's list: [2, 4, 1, 3, 5] using 1-based positions. Count the inversions of that list. The result is 3, so the rankings disagree on 3 pairs of films.