Sub topic 12
Counting Inversions During the Merge
This chapter assumes you already know the top-down merge sort and its merge step from earlier chapters. You should also be comfortable with recursion and Big-O notation. Here we reuse the merge to answer a different question: how far is a list from being sorted?
What an Inversion Is
An inversion is a pair of positions i < j where items[i] > items[j]. In other words, it is a pair of elements in the wrong order. A sorted list has zero inversions. A list sorted in reverse has the most possible, n(n-1)/2.
Take [2, 4, 1, 3, 5]. It has three inversions: (2, 1), (4, 1), and (4, 3).
Inversion counts measure how similar two rankings are. If two people rank the same ten films, the number of inversions between their lists tells you how much they disagree. The count is also the number of swaps insertion sort performs, so it predicts how much work that sort will do.
The Brute-Force Baseline
The obvious method checks every pair:
def count_brute(items):
n = len(items)
return sum(1 for i in range(n) for j in range(i + 1, n) if items[i] > items[j])
print(count_brute([2, 4, 1, 3, 5])) # 3This takes O(n²) time. For a million elements that is about 5 × 10¹¹ comparisons, which is too slow.
Where the Merge Helps
Split the list into a left half and a right half. Every inversion falls into one of three groups:
- Both elements are in the left half.
- Both elements are in the right half.
- One element is in each half, with the left one larger.
Recursion counts groups 1 and 2. Group 3 is the hard part, and the merge handles it at no extra cost.
During the merge, both halves are already sorted. Suppose right[j] is smaller than left[i] and gets taken first. Because the left half is sorted, every element from left[i] to the end of the left half is at least left[i], so each of them is greater than right[j]. Each one forms an inversion with right[j]. That is len(left) - i inversions, added in one step.
Sorting the halves does not change the group 3 count. Reordering within a half never moves an element from one side of the split to the other, so the cross pairs stay the same.
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 extra work at each merge is one addition per element taken from the right half. The recurrence is still T(n) = 2T(n/2) + O(n), so the total time is O(n log n).
Tracing the Final Merge
The recursive calls on [2, 4] and [1, 3, 5] find no inversions, so the answer is 3.
Common Errors
- Using
<instead of<=. With<, the merge takes equal elements from the right half first and counts them as inversions. Equal values are not inversions, so the count comes out too high. - Adding 1 instead of
len(left) - i. This counts only one inversion per right-half element and misses the rest. - Counting when the left element is taken. Inversions are added only when a right-half element moves ahead of the remaining left-half elements.
Test against count_brute on random inputs to catch these:
import random
for _ in range(1000):
data = [random.randint(0, 10) for _ in range(random.randint(0, 30))]
assert sort_and_count(data)[1] == count_brute(data)
print("all tests passed")Exercise
How many inversions does [5, 4, 3, 2, 1] have, and what does the final merge of [5, 4] (sorted as [4, 5]) with [3, 2, 1] (sorted as [1, 2, 3]) add?
Show answer
There are 10 inversions, which equals n(n-1)/2 for n = 5. The halves contribute 1 and 3. The final merge takes 1, 2, and 3 from the right while both 4 and 5 are still on the left, adding 2 + 2 + 2 = 6. The total is 1 + 3 + 6 = 10.
Exercise
If the merge used < instead of <=, what would sortandcount([1, 1]) return for the count, and why is that wrong?
Show answer
It would return 1. The right-half 1 is taken first while the left-half 1 is still waiting, so the pair is counted. The pair is not an inversion because 1 > 1 is false, so the correct count is 0.