Sort in O(n log n) and count inversions while merging.
Merging two sorted lists takes the smaller front value each time, and a value taken from the right passes every value still waiting on the left.
Use it when you must sort in n log n, or count pairs by a comparison of two values, or merge sorted runs. Signal words: count the pairs out of order, an earlier value is larger, a count for every element, sort a linked list.
Start: a list of zero or one value is sorted, with no pairs.
Step: sort each half, then merge by taking the smaller front value. Take from the left on a tie. When a value comes from the right, add the number of values waiting on the left.
Stop: when the halves are single values. The count is the left count, the right count, and the count across.
It does not need a stable method for a plain count, but the left-on-tie rule keeps equal values in order, which matters when you sort records.
Cost: O(n log n) time and O(n) extra space for the merge buffers. The recursion is log₂ n levels deep, which is 17 for 100,000 values.
def merge_sort(values):
# [1] A list of zero or one value is already sorted.
if len(values) <= 1:
return list(values)
# [2] Sort each half by the same method.
mid = len(values) // 2
left = merge_sort(values[:mid])
right = merge_sort(values[mid:])
# [3] Merge: repeatedly take the smaller front value. On a tie take the left one, which keeps equal values in order.
merged = []
i = 0
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
# [4] One half is used up: the rest of the other half is already in order.
merged += left[i:]
merged += right[j:]
return mergedpublic int[] mergeSort(int[] values) {
// [1] A list of zero or one value is already sorted.
if (values.length <= 1) {
return values.clone();
}
// [2] Sort each half by the same method.
int mid = values.length / 2;
int[] left = mergeSort(java.util.Arrays.copyOfRange(values, 0, mid));
int[] right = mergeSort(java.util.Arrays.copyOfRange(values, mid, values.length));
// [3] Merge: repeatedly take the smaller front value. On a tie take the left one, which keeps equal values in order.
int[] merged = new int[values.length];
int i = 0;
int j = 0;
int k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged[k++] = left[i++];
} else {
merged[k++] = right[j++];
}
}
// [4] One half is used up: the rest of the other half is already in order.
while (i < left.length) {
merged[k++] = left[i++];
}
while (j < right.length) {
merged[k++] = right[j++];
}
return merged;
}vector<int> mergeSort(vector<int>& values) {
// [1] A list of zero or one value is already sorted.
if (values.size() <= 1) {
return values;
}
// [2] Sort each half by the same method.
int mid = (int)values.size() / 2;
vector<int> leftHalf(values.begin(), values.begin() + mid);
vector<int> rightHalf(values.begin() + mid, values.end());
vector<int> left = mergeSort(leftHalf);
vector<int> right = mergeSort(rightHalf);
// [3] Merge: repeatedly take the smaller front value. On a tie take the left one, which keeps equal values in order.
vector<int> merged;
size_t i = 0;
size_t j = 0;
while (i < left.size() && j < right.size()) {
if (left[i] <= right[j]) {
merged.push_back(left[i++]);
} else {
merged.push_back(right[j++]);
}
}
// [4] One half is used up: the rest of the other half is already in order.
while (i < left.size()) {
merged.push_back(left[i++]);
}
while (j < right.size()) {
merged.push_back(right[j++]);
}
return merged;
}function mergeSort(values) {
// [1] A list of zero or one value is already sorted.
if (values.length <= 1) {
return [...values];
}
// [2] Sort each half by the same method.
const mid = Math.floor(values.length / 2);
const left = mergeSort(values.slice(0, mid));
const right = mergeSort(values.slice(mid));
// [3] Merge: repeatedly take the smaller front value. On a tie take the left one, which keeps equal values in order.
const merged = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged.push(left[i++]);
} else {
merged.push(right[j++]);
}
}
// [4] One half is used up: the rest of the other half is already in order.
while (i < left.length) {
merged.push(left[i++]);
}
while (j < right.length) {
merged.push(right[j++]);
}
return merged;
}def count_inversions(values):
def sort(a):
# [1] Zero or one value is already sorted and has no pairs.
if len(a) <= 1:
return a, 0
# [2] Sort each half and count the pairs inside each half.
mid = len(a) // 2
left, count_left = sort(a[:mid])
right, count_right = sort(a[mid:])
# [3] Merge. A value taken from the right passes every value still waiting on the left.
merged = []
i = 0
j = 0
across = 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
across += len(left) - i
merged += left[i:]
merged += right[j:]
# [4] The count is the pairs in each half plus the pairs across them.
return merged, count_left + count_right + across
return sort(values)[1]public long countInversions(int[] values) {
int[] a = values.clone();
return sortCount(a, new int[a.length], 0, a.length);
}
private long sortCount(int[] a, int[] tmp, int lo, int hi) {
// [1] Zero or one value is already sorted and has no pairs.
if (hi - lo <= 1) {
return 0;
}
// [2] Sort each half and count the pairs inside each half.
int mid = (lo + hi) / 2;
long count = sortCount(a, tmp, lo, mid) + sortCount(a, tmp, mid, hi);
// [3] Merge. A value taken from the right passes every value still waiting on the left.
int i = lo;
int j = mid;
int k = lo;
while (i < mid && j < hi) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
} else {
tmp[k++] = a[j++];
count += mid - i;
}
}
while (i < mid) {
tmp[k++] = a[i++];
}
while (j < hi) {
tmp[k++] = a[j++];
}
for (int t = lo; t < hi; t++) {
a[t] = tmp[t];
}
// [4] The count is the pairs in each half plus the pairs across them.
return count;
}static long long sortCount(vector<int>& a, vector<int>& tmp, int lo, int hi) {
// [1] Zero or one value is already sorted and has no pairs.
if (hi - lo <= 1) {
return 0;
}
// [2] Sort each half and count the pairs inside each half.
int mid = (lo + hi) / 2;
long long count = sortCount(a, tmp, lo, mid) + sortCount(a, tmp, mid, hi);
// [3] Merge. A value taken from the right passes every value still waiting on the left.
int i = lo;
int j = mid;
int k = lo;
while (i < mid && j < hi) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
} else {
tmp[k++] = a[j++];
count += mid - i;
}
}
while (i < mid) {
tmp[k++] = a[i++];
}
while (j < hi) {
tmp[k++] = a[j++];
}
for (int t = lo; t < hi; t++) {
a[t] = tmp[t];
}
// [4] The count is the pairs in each half plus the pairs across them.
return count;
}
long long countInversions(vector<int>& values) {
vector<int> a = values;
vector<int> tmp(a.size());
return sortCount(a, tmp, 0, (int)a.size());
}function sortCount(a, tmp, lo, hi) {
// [1] Zero or one value is already sorted and has no pairs.
if (hi - lo <= 1) {
return 0;
}
// [2] Sort each half and count the pairs inside each half.
const mid = Math.floor((lo + hi) / 2);
let count = sortCount(a, tmp, lo, mid) + sortCount(a, tmp, mid, hi);
// [3] Merge. A value taken from the right passes every value still waiting on the left.
let i = lo;
let j = mid;
let k = lo;
while (i < mid && j < hi) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
} else {
tmp[k++] = a[j++];
count += mid - i;
}
}
while (i < mid) {
tmp[k++] = a[i++];
}
while (j < hi) {
tmp[k++] = a[j++];
}
for (let t = lo; t < hi; t++) {
a[t] = tmp[t];
}
// [4] The count is the pairs in each half plus the pairs across them.
return count;
}
function countInversions(values) {
const a = [...values];
return sortCount(a, new Array(a.length), 0, a.length);
}This version writes left[i] < right[j] in the merge. On a tie it takes the right value, which counts equal values as inversions and changes the order of equal records.
This version writes across += 1 when a value comes from the right. It counts the values taken, not the pairs they make.
This version keeps the count in a 32-bit integer. A random list of 100,000 values has 2,510,312,633 inversions, and the largest 32-bit value is 2,147,483,647.
This version merges into a buffer and forgets to copy the buffer back into the list. The next level up then merges halves that are not sorted.
The app also sorts 1,000 playlists that arrive almost in order, each at most 5 places from where it belongs. On one seeded list, insertion sort makes 2,255 comparisons. Merge sort makes 5,470.
systemdesignmastery.dev/dsa/cheatsheets/merge-sort-and-inversions