Sort in O(n log n) and count inversions while merging.
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.
In this lesson you write merge sort, and you use its merge step to count inversions: pairs that are out of order. You learn why the merge step is cheap. That one idea sorts a long list in about n log n steps, and it counts a very large number of pairs without looking at each one.
You work on the music app. A "taste match" feature compares two listeners who each put the same songs in order. The match score is the number of pairs of songs that the two listeners put in opposite orders.
For a real pair of listeners the list has 100,000 songs. Checking one pair of songs takes about 1 microsecond.
Your team lead says: Give me the score for a few hundred thousand pairs of listeners tonight. Show me how you count.
Here is a short test. Your friend ranks six songs. You listen to them in the order that has the friend's ranks 3, 5, 1, 6, 2, 4. The score is the number of pairs where a song you play earlier has a higher friend rank than a song you play later.
So the task is this: count those pairs for 100,000 songs without checking every pair.
You have two piles of cards. Each pile is in order, smallest on top. You want one pile in order.
Look at the two top cards, take the smaller one, and put it on the new pile. Repeat until both piles are empty.
You never look deeper than the top cards, because each pile is already in order. That is the merge step of merge sort. The piles are the two halves of the list.
Two sorted piles of cards: look at the two top cards, take the smaller, and repeat until both piles are empty.
Before you write code, count the pairs for the six rankings by hand. It shows how many checks the count needs.
Solve it by hand: Six rankings: count the pairs by hand. The hand-solve sheet loads in your browser.
You take each position in turn and look at every later position.
The rankings are 3, 5, 1, 6, 2 and 4. For each position, count the later values that are smaller.
| Position | Value | Later values | Smaller than it | Total so far |
|---|---|---|---|---|
| 0 | 3 | 5 | 2 | 2 |
| 1 | 5 | 4 | 3 | 5 |
| 2 | 1 | 3 | 0 | 5 |
| 3 | 6 | 2 | 2 | 7 |
| 4 | 2 | 1 | 0 | 7 |
| 5 | 4 | 0 | 0 | 7 |
There are 7 pairs in opposite order, found with 15 checks. Look at what grows. Position 0 makes 5 checks, position 1 makes 4, and so on: n × (n − 1) / 2 checks in all.
Start with a correct version. It checks every pair.
def count_pairs_by_scan(values):
# [1] Start the count at zero.
total = 0
n = len(values)
# [2] Take each position i, and look at every later position j.
for i in range(n):
for j in range(i + 1, n):
# [3] A pair is out of order when the earlier value is larger.
if values[i] > values[j]:
total += 1
# [4] Return the count.
return totalpublic long countPairsByScan(int[] values) {
// [1] Start the count at zero.
long total = 0;
int n = values.length;
// [2] Take each position i, and look at every later position j.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// [3] A pair is out of order when the earlier value is larger.
if (values[i] > values[j]) {
total++;
}
}
}
// [4] Return the count.
return total;
}long long countPairsByScan(vector<int>& values) {
// [1] Start the count at zero.
long long total = 0;
int n = (int)values.size();
// [2] Take each position i, and look at every later position j.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// [3] A pair is out of order when the earlier value is larger.
if (values[i] > values[j]) {
total++;
}
}
}
// [4] Return the count.
return total;
}function countPairsByScan(values) {
// [1] Start the count at zero.
let total = 0;
const n = values.length;
// [2] Take each position i, and look at every later position j.
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// [3] A pair is out of order when the earlier value is larger.
if (values[i] > values[j]) {
total++;
}
}
}
// [4] Return the count.
return total;
}This is correct. It makes n × (n − 1) / 2 checks, whatever the order: O(n²). The team keeps it as the reference.
Now check the real size.
A real pair of listeners has 100,000 songs, and one check takes 1 microsecond.
Here is the count:
So one pair of listeners already takes more than an hour.
Predict the cost
Q One pair of listeners has 100,000 songs. Checking every pair of songs takes 4,999,950,000 checks at 1 microsecond each. About how long is that?
Answer: C
4,999,950,000 microseconds is 4,999.95 seconds. Divided by 60, that is about 83.3 minutes for one pair of listeners.
The first attempt is correct, but it looks at pairs one at a time. Sorting looks at the whole list at once, and it can count the pairs on the way.
Call a pair in opposite order an inversion: positions i < j with values[i] > values[j]. A sorted list has none. Every step of a sort that fixes an inversion brings the list closer to sorted, so sorting and counting are close relatives.
Merge sort splits the list in halves, sorts each half by the same method, and merges the two sorted halves. A list of zero or one value is already sorted, so the splitting stops there.
The merge is cheap. Both halves are sorted, so you only look at their front values. Take the smaller one, and move on. Each value is written once.
Dry run: One merge: two sorted halves become one. The step-by-step player loads in your browser.
The trace shows one merge of the sorted halves [2, 4, 7, 8] and [1, 3, 5, 6]. The values come out in order: 1, 2, 3, 4, 5, 6 and then the rest. The merge made 6 comparisons for 8 values.
A merge compares the two front values and takes the smaller one, so each value is written once.
Now look at the moment a value comes from the right half. Take the 1. It sits after the whole left half in the original list.
Every value still waiting on the left is larger than 1, so each one forms an inversion with it. That is 4 inversions in one step, and no pair was checked.
Race: Checking every pair against merge sort. The operation counter loads in your browser.
The race counts comparisons. At 1,000 rankings, checking every pair makes 499,500, and merge sort makes 8,735 on a random list. At 10,000 rankings the counts are 49,995,000 against 120,392.
A value taken from the right half passes every value still waiting on the left, so add that many inversions.
The rankings are [4, 7, 2, 8, 1, 6, 3, 5]. The sort splits the list down to single values, then merges upward. After each merge the total of inversions found so far is shown. The player stops at five merges and asks you to predict.
Dry run: Predict each merge: eight rankings. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Merge | Left | Right | Found across | Total so far |
|---|---|---|---|---|
| 1 | [4] | [7] | 0 | 0 |
| 2 | [2] | [8] | 0 | 0 |
| 3 | [4, 7] | [2, 8] | 2 | 2 |
| 4 | [1] | [6] | 0 | 2 |
| 5 | [3] | [5] | 0 | 2 |
| 6 | [1, 6] | [3, 5] | 2 | 4 |
| 7 | [2, 4, 7, 8] | [1, 3, 5, 6] | 11 | 15 |
The count is 15, and checking every pair finds the same 15. Look at merge 3. The 2 comes from the right while 4 and 7 wait on the left, so it adds 2. The 8 is taken after the 7, with nothing waiting, so it adds nothing.
Predict the merge
Q In a merge, the left half is [4, 7] and the right half is [2, 8]. The 2 is taken from the right first. How many inversions does that step find?
Answer: B
Both 4 and 7 come before the 2 in the original list and are larger than it, so the 2 forms an inversion with each of them.
Merge sort does the splitting log₂ n times, and each level merges n values. Counting adds one subtraction to each step. So the count is free.
Here is the rule that keeps the merge correct. Every line of the templates exists to protect it.
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.
At the start both halves are sorted, so the front values are their smallest. The smaller front value is the smallest value left, so it comes next in the merged list. When it comes from the right, every value still waiting on the left is larger, and they all come before it in the original list. Those are exactly the inversions between the halves.
Every pair of positions is split by the middle exactly once in the recursion: inside the left half, inside the right half, or across them. The total is the left count, plus the right count, plus the count across.
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;
}Exercise · Put it in order: Merge two sorted piles. Arrange the lines into a function that merges two sorted lists into one sorted list.
def merge_sorted(left, right):
merged = []
i, j = 0, 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
merged += left[i:] + right[j:]
return merged
while i < len(left) or j < len(right):The same merge counts the pairs. One line is new: when a value comes from the right, add the number of values waiting on the left.
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);
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Predict the output: How many pairs does this merge count?. The left pile is 3, 8, 9 and the right pile is 1, 5, 10, both sorted. This merge adds the number of values waiting on the left each time a right value goes first. What does it print?
left = [3, 8, 9]
right = [1, 5, 10]
i = j = 0
across = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
i += 1
else:
across += len(left) - i
j += 1
print(across)Exercise · Find the bug: The pairs counted from the wrong pile. This function counts the pairs across two sorted piles, where a left value is larger than a right value. It undercounts. Which line is wrong?
def count_across(left, right):
i, j = 0, 0
across = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
i += 1
else:
j += 1
across += len(left) - j
return acrossBoth templates answer one question: what do I do when I take a value from the right? You can decide that before you write code.
Then check the two ends: what do the templates do on an empty list, and on a list of equal values?
| Question | Use | Why |
|---|---|---|
| Sort a long list | Template 1 | n log n comparisons |
| Count out-of-order pairs | Template 2 | The merge counts them for free |
| A different test for a pair | Count before the merge | Sorted halves give a forward pointer |
| A count for every element | Sort positions | Each value stays tied to where it started |
A parcel belt scan lists five parcels by the slot each one must reach: 3, 1, 2, 5, 4. A worker can swap two neighbouring parcels. The fewest swaps is the number of inversions, since each neighbour swap fixes at most one pair.
Count them with Template 2. The halves [3, 1] and [2, 5, 4] hold 1 inversion each. The last merge joins [1, 3] and [2, 4, 5].
| Step | Left waiting | Right waiting | Taken | Added |
|---|---|---|---|---|
| 1 | [1, 3] | [2, 4, 5] | 1 from the left | 0 |
| 2 | [3] | [2, 4, 5] | 2 from the right | 1 |
| 3 | [3] | [4, 5] | 3 from the left | 0 |
| 4 | [] | [4, 5] | the rest | 0 |
The total is 1 + 1 + 1 = 3 swaps. Taking the 2 passes the 3, which is the only pair across the halves.
Real data brings edge cases.
For values = [] or values = [5], the first check in the template stops the recursion. Sorting returns the list as it is, and the count is 0.
For values = [7, 7, 7], every comparison is a tie, and a tie takes the left value. No value comes from the right while another waits on the left, so the count is 0 and the order does not change.
For values = [6, 5, 4, 3, 2, 1], every pair is out of order, so the count is 15, which is n × (n − 1) / 2. For 100,000 values in reverse order it is 4,999,950,000. That is past the largest 32-bit integer, 2,147,483,647.
For values = [1, 2, 3, 4, 5] the count is 0, because every comparison takes the left value. Merge sort still makes its comparisons: 4,932 for 1,000 sorted values.
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.
Counterexample: for values = [5, 5, 5] it counts 3 inversions. The correct count is 0, because no earlier value is larger than a later one. Sorting the records (2, a), (1, b), (2, c) by number, it returns (1, b), (2, c), (2, a). With <= the result is (1, b), (2, a), (2, c), so equal records keep their order.
The fix is <=. A tie takes the left value.
This version writes across += 1 when a value comes from the right. It counts the values taken, not the pairs they make.
Counterexample: for the eight rankings [4, 7, 2, 8, 1, 6, 3, 5] it counts 7. The correct count is 15, because a value from the right passes every value waiting on the left.
Add len(left) − i: the number of values still waiting.
Taking the right value on a tie counts equal values as inversions: five, five, five gives 3 instead of 0.
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.
Counterexample: the count wraps to −1,784,654,663 in a 32-bit integer. The same code with a 64-bit counter gives 2,510,312,633.
Use long in Java and long long in C++. Python integers do not overflow. JavaScript numbers hold integers exactly up to 2^53, which is far above any count here.
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.
Counterexample: for the six rankings [3, 5, 1, 6, 2, 4] it counts 3. The correct count is 7.
Copy the merged range back before returning. Template 2 does this with its last loop in Java, C++ and JavaScript, and the Python version returns the merged list.
Exercise · Break it: Find the list this merge sort shortens. This merge sort copies the rest of the left half after the merge loop, but not the rest of the right half. Find a list it gets wrong.
def merge_sort(values):
if len(values) <= 1:
return list(values)
mid = len(values) // 2
left = merge_sort(values[:mid])
right = merge_sort(values[mid:])
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
merged += left[i:]
return mergedThe 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.
Merge sort does not use the order that is already there. Insertion sort pays for the inversions, and a nearly sorted list has few of them. Pick the method by the data.
Your team lead brings four product changes. Each one asks what to do when a value comes from the right.
The team wants, for each song in your order, the number of later songs your friend ranks lower. Sort the positions, not the values. When a left song is taken, add the number of right songs already taken to it. This is LeetCode 315: Count of Smaller Numbers After Self, and the problem "Count smaller later values" practises it.
A strong disagreement is a pair where your song has more than twice the friend's rank of the later one. The merge's own comparison cannot find it. Count first, with a pointer that moves forward over the sorted right half, then merge. This is LeetCode 493: Reverse Pairs.
A play queue is a linked chain. Merge sort needs no array: find the middle with two pointers, sort each half, and relink the nodes while merging. It uses no extra list (LeetCode 148: Sort List).
Sort chunks that fit, write each as a sorted run, and merge the runs in passes. Each pass reads the whole file once, and the merge step is the same. The problem "Sort a large file in chunks" practises it.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how merge sort works and how you count inversions while merging. Then say what the count costs for 100,000 values. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
Merge sort splits the list, sorts each half and merges them by taking the smaller front value, so it costs about n log n. An inversion is a pair with a larger earlier value. When a value comes from the right, every value still waiting on the left is larger and earlier, so I add that number. I take the left on a tie and use 64 bits: about 1.5 million comparisons for 100,000 values, not 5 billion.
Checking every pair of values costs about n squared over 2, which is nearly 5 billion for 100,000 values. So I count while I merge sort.
Merge sort splits the list in halves, sorts each half the same way, and merges them. A merge takes the smaller of the two front values, so each value is written once, and the sort costs n log n.
An inversion is a pair where the earlier value is larger. When a value comes from the right half, every value still waiting on the left is larger and earlier. I add that number to the count.
I take from the left on a tie, so equal values are not counted and stay in order. I keep the count in a 64-bit integer, because it can pass two billion.
Checkpoint · Merge sort
Q1/3 How does merge sort sort a list?
Answer: B
Merge sort splits the list down to zero or one value, which is sorted, and then merges sorted halves back up.
Q2/3 Two sorted halves hold 1,000 values in all. About how many steps does merging them take?
Answer: C
A merge compares the two front values and takes the smaller one, so each value is written once. Merging n values costs about n steps.
Q3/3 What is an inversion?
Answer: C
An inversion is a pair that is out of order: the earlier value is larger. A sorted list has none.
Checkpoint · Counting while merging
Q1/3 The left half is [4, 7] and the right half is [2, 8]. The 2 is taken from the right. How many inversions does that step find?
Answer: B
Both 4 and 7 are still waiting on the left. They come earlier in the list and are larger than 2, so the 2 forms an inversion with each.
Q2/3 How many inversions does the list [2, 1, 2, 1, 2] have?
Answer: C
The pairs are (2, 1) at positions 0 and 1, (2, 1) at positions 0 and 3, and (2, 1) at positions 2 and 3. Equal values do not count.
Q3/3 In the merge, the left value is 5 and the right value is 5. Which one should be taken, and why?
Answer: B
Taking the left value on a tie keeps equal values in their order and adds nothing to the count. Taking the right one would count [5, 5, 5] as 3 inversions.
Checkpoint · Scale and variations
Q1/4 One random list of 100,000 values has 2,510,312,633 inversions. Which type holds the count?
Answer: C
The count is larger than 2,147,483,647, so a 32-bit integer wraps to a negative number. Use long in Java and long long in C++.
Q2/4 For 100,000 values, about how many comparisons does merge sort need, against checking every pair?
Answer: B
A run on a random list took 1,536,247 comparisons. Checking every pair takes 100,000 × 99,999 / 2, which is 4,999,950,000.
Q3/4 You must count pairs where an earlier value is more than double a later one. What changes?
Answer: C
The merge advances by a different test, so the doubling test needs its own pointer over the sorted halves, before the merge.
Q4/4 A merge adds 1 to the count each time a value is taken from the right. For [4, 7, 2, 8, 1, 6, 3, 5] it returns 7. The correct count is 15. What is wrong?
Answer: B
A value taken from the right passes every larger value waiting on the left, so it makes that many inversions, not one.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Merge sort, pass by pass, on ticket times | Observe | Easy | The merge step, level by level |
| 2 | Sort a large file in chunks | Bank | Medium | Merging runs of any length |
| 3 | Count pairs with a sharp drop | Feed | Hard | Counting before the merge with a pointer |
| 4 | Count smaller later values | Stream | Hard | Sorting positions, crediting the left value |
A built extra, "Pairs processed out of order", counts inversions in a chat log with Template 2.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.