Sub topic 10
Counting Inversions by Extending Merge Sort
This chapter assumes you know merge sort from the previous chapter, can trace a recursive function, and can read Big-O notation. It shows how adding one line to the merge step turns merge sort into an inversion counter.
What an Inversion Is
An inversion in a list a is a pair of positions i < j where a[i] > a[j]. It is a pair of elements that are in the wrong order. A sorted list has zero inversions. A list sorted in reverse has the most possible, n(n-1)/2. The inversion count shows how far a list is from sorted. Ranking systems use it to compare two people's orderings of the same items.
The obvious method checks every pair, which takes O(n²) time. Divide and conquer brings this down to O(n log n).
Splitting the Count Three Ways
Split the list at the midpoint. Every inversion falls into exactly one of three groups:
- Both elements are in the left half (left inversions).
- Both elements are in the right half (right inversions).
- One element is in each half (split inversions).
Recursion handles the first two groups. Counting split inversions one pair at a time would cost O(n²). If both halves are already sorted, though, the merge step finds all of them in linear time.
The Key Observation
During the merge, suppose right[j] is smaller than left[i]. The left half is sorted, so every element from left[i] to the end of left is also larger than right[j]. All of those elements came before right[j] in the original list. That is len(left) - i split inversions, counted in one step.
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
print(sort_and_count([2, 4, 1, 3, 5])[1]) # 3The merge step still does O(n) work. The recurrence stays T(n) = 2T(n/2) + O(n), so the total time is O(n log n).
A Worked Trace
For [2, 4, 1, 3, 5], the halves are [2, 4] and [1, 3, 5]. Neither half has any inversions inside it. During the merge:
| Compare | Take | Split inversions added |
|---|---|---|
| 2 vs 1 | 1 | 2 (from 2 and 4) |
| 2 vs 3 | 2 | 0 |
| 4 vs 3 | 3 | 1 (from 4) |
| 4 vs 5 | 4 | 0 |
The total is 0 + 0 + 3 = 3. The three inversions are (2,1), (4,1), and (4,3).
Common Errors
- Adding 1 instead of
len(left) - icounts only one of the inversions thatright[j]forms with the left half. - Counting during a merge of unsorted halves gives wrong answers. The shortcut depends on the left half being sorted, so the function must return the sorted list along with the count.
- Forgetting to add
inv_leftandinv_rightdrops every inversion that sits entirely inside one half.
Exercise
What does sortandcount([5, 4, 3, 2, 1]) return as its count, and why?
Show answer
It returns 10. The list is in reverse order, so every one of the n(n-1)/2 = 5·4/2 = 10 pairs is an inversion.
Exercise
Give the inversion count of [3, 1, 3, 2] and say which comparison operator keeps the tie between the two 3s from being counted.
Show answer
The count is 3: (3,1), (3,2), and (3,2). The pair of 3s is not an inversion because they are equal. Using <= in the merge takes the left 3 first on a tie, so that pair is never counted.