Algorithms · Divide and Conquer: Max-Min, Maximum Subarray, Inversions and Fast Exponentiation
Counting Inversions with Merge Sort
4.1 Definition
An inversion is a pair with and . The inversion count measures how far the array is from sorted; it equals the number of adjacent swaps needed by insertion/bubble sort.
4.2 Method
Modify merge sort: during the merge of left half and right half , when we take an element from because it is smaller than the current , then and every remaining element of (there are len(L) - i of them) form inversions with that element. Add len(L) - i to the count.
4.3 Worked example,
Array: A = [2, 4, 1, 3, 5, 0]. Split into [2,4,1] and [3,5,0].
Left half [2,4,1] → split [2] and [4,1].
[4,1]→ split[4],[1]; merge: 1 < 4, take 1 from right, remaining left = 1 element (4), add 1. Merged[1,4].- Merge
[2]with[1,4]: compare 2 vs 1 → take 1, remaining left = 1 (2), add 1. Compare 2 vs 4 → take 2. Take 4. Merged[1,2,4]. Left-half inversions = .
Right half [3,5,0] → split [3] and [5,0].
[5,0]: take 0, remaining left = 1, add 1. Merged[0,5].- Merge
[3]with[0,5]: 3 vs 0 → take 0, remaining left = 1, add 1. 3 vs 5 → take 3. Take 5. Merged[0,3,5]. Right-half inversions = .
Final merge [1,2,4] with [0,3,5]:
| Step | Compare | Take | Remaining in left | Add |
|---|---|---|---|---|
| 1 | 1 vs 0 | 0 | 3 (1,2,4) | 3 |
| 2 | 1 vs 3 | 1 | 2 (2,4) | 0 |
| 3 | 2 vs 3 | 2 | 1 (4) | 0 |
| 4 | 4 vs 3 | 3 | 1 (4) | 1 |
| 5 | 4 vs 5 | 4 | 0 | 0 |
| 6 | — | 5 | 0 | 0 |
Cross inversions = .
Total .
Verification by brute force. Pairs , , with :
- (2): (1) ✓, (0) ✓ → 2
- (4): (1) ✓, (3) ✓, (0) ✓ → 3
- (1): (0) ✓ → 1
- (3): (0) ✓ → 1
- (5): (0) ✓ → 1
- : none
Total . ✓ Matches.