Arrays & Hashing · Pattern 8 of 26
Merge sort, and counting while you merge
Merge sort splits, sorts both halves, then merges. During the merge you know which left values are bigger than a right value, which counts inversions and similar pairs in O(n log n).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Count pairs i < j with a[i] > a[j] (or a[i] > 2·a[j])
- Sort with guaranteed O(n log n)
- Rearrange stably, keeping relative order
The template
long countInversions(int[] a) {
return sort(a, new int[a.length], 0, a.length - 1);
}
long sort(int[] a, int[] tmp, int lo, int hi) {
if (lo >= hi) return 0;
int mid = (lo + hi) / 2;
long count = sort(a, tmp, lo, mid) + sort(a, tmp, mid + 1, hi);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else { count += mid - i + 1; tmp[k++] = a[j++]; } // a[i..mid] are all > a[j]
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
return count;
} def count_inversions(a):
def sort(lo, hi): # sorts a[lo:hi], returns inversions inside
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
count = sort(lo, mid) + sort(mid, hi)
merged, i, j = [], lo, mid
while i < mid and j < hi:
if a[i] <= a[j]:
merged.append(a[i]); i += 1
else:
count += mid - i # a[i:mid] are all > a[j]
merged.append(a[j]); j += 1
merged += a[i:mid] + a[j:hi]
a[lo:hi] = merged
return count
return sort(0, len(a)) long long mergeCount(vector<int>& a, vector<int>& tmp, int lo, int hi) {
if (lo >= hi) return 0;
int mid = (lo + hi) / 2;
long long count = mergeCount(a, tmp, lo, mid) + mergeCount(a, tmp, mid + 1, hi);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else { count += mid - i + 1; tmp[k++] = a[j++]; } // a[i..mid] are all > a[j]
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
return count;
}
long long countInversions(vector<int>& a) {
vector<int> tmp(a.size());
return mergeCount(a, tmp, 0, (int)a.size() - 1);
} function countInversions(a) {
const tmp = new Array(a.length);
const sort = (lo, hi) => {
if (lo >= hi) return 0;
const mid = (lo + hi) >> 1;
let count = sort(lo, mid) + sort(mid + 1, hi);
let i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else { count += mid - i + 1; tmp[k++] = a[j++]; } // a[i..mid] are all > a[j]
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
return count;
};
return sort(0, a.length - 1);
} The variations
-
1Count pairs while merging
When a right value is taken before left values, every remaining left value forms a pair with it. For a[i] > 2·a[j], count with a second pointer before the merge.
Now you solve -
2Merge sort itself, and stable rearranging
Split, sort halves, merge. Merging keeps equal elements in order, which is how you move negatives before positives without changing their relative order.
Now you solve
Mistakes to avoid
- Counting with
<instead of<=: equal values are not inversions. - Using int for the count: n = 10⁵ gives up to 5·10⁹ inversions.
- For reverse pairs (a[i] > 2·a[j]), counting inside the merge loop instead of in a separate pass before merging.
Lesson done
Next: Dutch national flag: three-way partition →Mark it done once you can write the template from memory and you have solved the worked examples yourself.