What is Count Inversions
An inversion is a pair of indices i < j with a[i] > a[j]. Return how many such pairs exist. Merging two sorted halves counts the cross pairs in linear time: when the right head is smaller, it forms an inversion with every value still waiting on the left.
2 4 1 3 5 3
Approach
An inversion is a pair i < j with a[i] > a[j]. Checking every pair is quadratic. Merge sort already walks those pairs while it merges two sorted halves.
Taking the left head adds nothing, because the right half is sorted and the right head is not smaller. The total is the two recursive counts plus the cross count.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n log n) | The same recursion as merge sort, plus a constant-time add. |
| Memory | O(n) | The merge builds a new run. |
Implementation
def sort_count(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, c1 = sort_count(a[:mid])
right, c2 = sort_count(a[mid:])
out, i, j, cross = [], 0, 0, 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])
cross += len(left) - i
j += 1
out.extend(left[i:]); out.extend(right[j:])
return out, c1 + c2 + cross