Explain why comparison sorts need about n log n comparisons.
Use it when you must put items in order, or answer a question about their order, and the only tool is comparing two items. Signal words: the fewest comparisons any method needs, n factorial orders, two answers for each comparison.
Start count the answers the method must tell apart. For a full sort that is n!.
Step each comparison at most doubles the endings, so k comparisons give at most 2^k endings. Find the smallest k with 2^k at least the number of answers.
Stop the lower bound is that k. A method that uses about k comparisons is nearly the best possible.
It does not limit a method that never compares items, such as counting sort. It is a worst-case bound, so one lucky input can need far fewer comparisons.
Cost: the floor is log2(n!) rounded up, which is about n log2 n − 1.44 n. It grows like n log n, O(n log n).
In this lesson you learn what a sort can know. A comparison sort learns about the order only by comparing two items at a time. You count how many comparisons any method needs, and you see why that count cannot drop below about n log n.
You work on the photo contest of a travel app. The contest has 1,000 entries, and the editors must rank all of them from the weakest photo to the strongest.
An editor can look at only two photos at a time, and picks the stronger one. One such comparison takes 10 seconds. The editors cannot give a photo a score, only compare.
Your team lead says: Plan the editors' week. Tell me how many comparisons the ranking needs, and whether anyone could do it with fewer.
Here is a short test: 4 photos with the hidden scores 31, 12, 47 and 20. The ranking is 12, 20, 31, 47.
So the task is this: rank the photos with as few comparisons as you can, and find out how few are possible.
In the guessing game, a friend thinks of a whole number from 1 to 1,000, and you may ask only yes-or-no questions. You can always find it in 10 questions: ask "is it above 500?", then halve again.
Ten questions are enough because each answer at most halves the options. Ten yes-or-no answers can tell 2^10 = 1,024 different numbers apart. A comparison is one yes-or-no question about two photos. The numbers are the possible orders of the photos.
Like twenty questions: every yes or no answer halves the options, so ten answers tell a thousand numbers apart.
Before you write code, rank the four photos by hand. It shows how many comparisons you spend.
Solve it by hand: Four photos: rank them with few comparisons. The hand-solve sheet loads in your browser.
First try the method most people reach for. You compare every photo with every other photo, once, and count how many photos each one beats.
Hidden scores: 31, 12, 47 and 20. All six pairs are compared.
| Comparison | Pair | Stronger photo |
|---|---|---|
| 1 | 31 and 12 | 31 |
| 2 | 31 and 47 | 47 |
| 3 | 31 and 20 | 31 |
| 4 | 12 and 47 | 47 |
| 5 | 12 and 20 | 20 |
| 6 | 47 and 20 | 47 |
The wins are 2 for photo 31, 0 for photo 12, 3 for photo 47 and 1 for photo 20. Sorted by wins, the ranking is 12, 20, 31, 47.
You made 6 comparisons for 4 photos. Look at what grows. A list of n photos has n × (n − 1) / 2 pairs.
Start with a correct version. Compare every pair once, and count the wins.
def rank_all_pairs(scores):
n = len(scores)
wins = [0] * n
for a in range(n): # every pair, once
for b in range(a + 1, n):
if scores[a] > scores[b]: # one comparison
wins[a] += 1
else:
wins[b] += 1
return wins # the scores are all different, so the wins give the ranksThis is correct. It makes n × (n − 1) / 2 comparisons: O(n²). The team keeps it as the reference.
Now check the real size.
The contest has 1,000 photos, and one comparison takes an editor 10 seconds.
Here is the count:
So the ranking would keep the editors busy for almost two months, and the contest closes this week.
Predict the cost
Q The contest has 1,000 photos, and the first attempt compares every pair at 10 seconds each. About how long does the first attempt take?
Answer: C
There are 1,000 × 999 / 2 = 499,500 pairs. At 10 seconds each that is 4,995,000 seconds, or about 57.8 days.
The first attempt is correct, but it asks about many pairs whose answer was already clear. Now count what a ranking really needs to find out.
Think about what the editors must find out. Four photos can be in 4 × 3 × 2 × 1 = 24 different orders, and the method must end with the right one.
Every comparison has two answers. After one comparison there are at most 2 groups of orders left, after two comparisons at most 4 endings, and after k comparisons at most 2^k endings.
Each order needs its own ending. If two orders shared an ending, the method would give the same ranking for both, and it would be wrong for one of them. So 2^k must be at least 24.
| Comparisons k | Endings 2^k | Enough for 24 orders? |
|---|---|---|
| 3 | 8 | no |
| 4 | 16 | no |
| 5 | 32 | yes |
No method can rank 4 photos in 4 comparisons, because 16 endings cannot cover 24 orders. At least 5 are needed, and binary insertion needs at most 5 for 4 photos. The first attempt used 6.
For 1,000 photos the same count gives a floor of 8,530 comparisons, which is 85,300 seconds, or 23.7 hours. Binary insertion needs at most 8,977, or 24.9 hours.
Race: Compare every pair, binary insertion, and the lower bound. The operation counter loads in your browser.
The race counts the worst case. At 1,000 photos, comparing every pair makes 499,500 comparisons, binary insertion makes 8,977, and no method can make fewer than 8,530. At 100 photos the three counts are 4,950, 573 and 525.
Four photos have 24 orders, and k comparisons give at most 2^k endings, so 16 are too few and 32 are enough.
The scores are [52, 17, 40, 8, 33, 25]: six photos. The method keeps the front of the list ranked. It takes the next photo and compares it with the middle of the ranked part, halving a window each time. The player stops at five steps and asks you to predict.
Dry run: Predict each step: six photos. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Photo | Ranked part before | Comparisons for this photo | Total so far |
|---|---|---|---|
| 17 | [52] | 1 | 1 |
| 40 | [17, 52] | 2 | 3 |
| 8 | [17, 40, 52] | 2 | 5 |
| 33 | [8, 17, 40, 52] | 2 | 7 |
| 25 | [8, 17, 33, 40, 52] | 2 | 9 |
The method ranks six photos in 9 comparisons. The floor for six photos is 10, which is above 9. This is possible because the floor is for the worst case, and these six photos were not the worst order.
Every comparison method is a tree of questions. The method asks a question, follows the answer, and asks the next question. Each ending at the bottom is one ranking.
Run binary insertion on all six orders of three photos, and count the comparisons for each order:
| Order of the three scores | Comparisons used |
|---|---|
| 1, 2, 3 | 2 |
| 2, 1, 3 | 2 |
| 1, 3, 2 | 3 |
| 2, 3, 1 | 3 |
| 3, 1, 2 | 3 |
| 3, 2, 1 | 3 |
There are 6 endings, and the deepest takes 3 comparisons. The tree cannot be shallower, because a tree of depth 2 has only 4 endings. The depth of the tree is the worst-case number of comparisons.
Here is every size from 1 to 8 photos. The last two columns come from running binary insertion on every possible order of the photos.
| Photos n | Orders n! | Floor: smallest k with 2^k ≥ n! | Binary insertion, worst order | Compare every pair |
|---|---|---|---|---|
| 1 | 1 | 0 | 0 | 0 |
| 2 | 2 | 1 | 1 | 1 |
| 3 | 6 | 3 | 3 | 3 |
| 4 | 24 | 5 | 5 | 6 |
| 5 | 120 | 7 | 8 | 10 |
| 6 | 720 | 10 | 11 | 15 |
| 7 | 5,040 | 13 | 14 | 21 |
| 8 | 40,320 | 16 | 17 | 28 |
Binary insertion matches the floor up to 4 photos and is one comparison above it from 5 to 8. Comparing every pair falls behind fast. The floor itself grows like n log n.
Here is the rule that gives every lower bound in this lesson. Both templates use it.
After k comparisons a method has at most 2^k endings, and sorting n items needs n! of them, so 2^k must reach n!.
At the start there are no comparisons, one ending, and n! orders to tell apart. Each comparison at most doubles the endings. The method can stop only when the endings cover the orders.
So no method can use fewer than the smallest k with 2^k ≥ n! comparisons in the worst case. Taking the logarithm in base 2 gives the same number: k is log2(n!) rounded up. It is a floor: it does not promise that some method meets it exactly.
Use it when you must put items in order, or answer a question about their order, and the only tool is comparing two items. Signal words: the fewest comparisons any method needs, n factorial orders, two answers for each comparison.
Start: count the answers the method must tell apart. For a full sort that is n!.
Step: each comparison at most doubles the endings, so k comparisons give at most 2^k endings. Find the smallest k with 2^k at least the number of answers.
Stop: the lower bound is that k. A method that uses about k comparisons is nearly the best possible.
It does not limit a method that never compares items, such as counting sort. It is a worst-case bound, so one lucky input can need far fewer comparisons.
Cost: the floor is log2(n!) rounded up, which is about n log2 n − 1.44 n. It grows like n log n, O(n log n).
The orders of n items come to n!, and a long integer holds n! up to n = 20. In JavaScript the code uses BigInt, because n! passes the exact range of a number at n = 19.
def comparison_floor(n):
# [1] Count the orders: n! of them, which a 64-bit integer holds up to n = 20.
orders = 1
for i in range(2, n + 1):
orders *= i
# [2] With no comparison there is one ending.
endings = 1
k = 0
# [3] Each comparison at most doubles the endings: stop when every order can have its own.
while endings < orders:
endings *= 2
k += 1
# [4] No method can use fewer than k comparisons in the worst case.
return kpublic int comparisonFloor(int n) {
// [1] Count the orders: n! of them, which a 64-bit integer holds up to n = 20.
long orders = 1;
for (int i = 2; i <= n; i++) {
orders *= i;
}
// [2] With no comparison there is one ending.
long endings = 1;
int k = 0;
// [3] Each comparison at most doubles the endings: stop when every order can have its own.
while (endings < orders) {
endings *= 2;
k++;
}
// [4] No method can use fewer than k comparisons in the worst case.
return k;
}int comparisonFloor(int n) {
// [1] Count the orders: n! of them, which a 64-bit integer holds up to n = 20.
long long orders = 1;
for (int i = 2; i <= n; i++) {
orders *= i;
}
// [2] With no comparison there is one ending.
long long endings = 1;
int k = 0;
// [3] Each comparison at most doubles the endings: stop when every order can have its own.
while (endings < orders) {
endings *= 2;
k++;
}
// [4] No method can use fewer than k comparisons in the worst case.
return k;
}function comparisonFloor(n) {
// [1] Count the orders: n! of them, which a 64-bit integer holds up to n = 20.
let orders = 1n;
for (let i = 2; i <= n; i++) {
orders *= BigInt(i);
}
// [2] With no comparison there is one ending.
let endings = 1n;
let k = 0;
// [3] Each comparison at most doubles the endings: stop when every order can have its own.
while (endings < orders) {
endings *= 2n;
k++;
}
// [4] No method can use fewer than k comparisons in the worst case.
return k;
}Exercise · Put it in order: The fewest comparisons for n items. Arrange the lines into a function that returns the fewest comparisons any method needs to rank n items in the worst case.
def comparison_floor(n):
orders = 1
for i in range(2, n + 1):
orders *= i
endings = 1
k = 0
while endings < orders:
endings *= 2
k += 1
return k
endings += 2Binary insertion keeps the front of the list ranked. For each next item it searches the ranked part with the window from the binary-search lesson, and every look at a middle item is one comparison.
def binary_insertion_count(values):
# [1] Work on a copy; the front part of it is always in order.
ranked = list(values)
count = 0
# [2] Take each item in turn and search the ranked front part for its place.
for i in range(1, len(ranked)):
x = ranked[i]
lo = 0
hi = i
# [3] Compare with the middle of the window: one comparison, and half the window is ruled out.
while lo < hi:
mid = lo + (hi - lo) // 2
count += 1
if ranked[mid] < x:
lo = mid + 1
else:
hi = mid
# [4] Shift the larger items right and put x in its place.
j = i
while j > lo:
ranked[j] = ranked[j - 1]
j -= 1
ranked[lo] = x
# [5] Return the comparisons used.
return countpublic int binaryInsertionCount(int[] values) {
// [1] Work on a copy; the front part of it is always in order.
int[] ranked = values.clone();
int count = 0;
// [2] Take each item in turn and search the ranked front part for its place.
for (int i = 1; i < ranked.length; i++) {
int x = ranked[i];
int lo = 0;
int hi = i;
// [3] Compare with the middle of the window: one comparison, and half the window is ruled out.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
count++;
if (ranked[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [4] Shift the larger items right and put x in its place.
int j = i;
while (j > lo) {
ranked[j] = ranked[j - 1];
j--;
}
ranked[lo] = x;
}
// [5] Return the comparisons used.
return count;
}int binaryInsertionCount(vector<int>& values) {
// [1] Work on a copy; the front part of it is always in order.
vector<int> ranked = values;
int count = 0;
// [2] Take each item in turn and search the ranked front part for its place.
for (int i = 1; i < (int)ranked.size(); i++) {
int x = ranked[i];
int lo = 0;
int hi = i;
// [3] Compare with the middle of the window: one comparison, and half the window is ruled out.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
count++;
if (ranked[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [4] Shift the larger items right and put x in its place.
int j = i;
while (j > lo) {
ranked[j] = ranked[j - 1];
j--;
}
ranked[lo] = x;
}
// [5] Return the comparisons used.
return count;
}function binaryInsertionCount(values) {
// [1] Work on a copy; the front part of it is always in order.
const ranked = [...values];
let count = 0;
// [2] Take each item in turn and search the ranked front part for its place.
for (let i = 1; i < ranked.length; i++) {
const x = ranked[i];
let lo = 0;
let hi = i;
// [3] Compare with the middle of the window: one comparison, and half the window is ruled out.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
count++;
if (ranked[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [4] Shift the larger items right and put x in its place.
let j = i;
while (j > lo) {
ranked[j] = ranked[j - 1];
j--;
}
ranked[lo] = x;
}
// [5] Return the comparisons used.
return count;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The window that reaches too far. This binary insertion should count 1 comparison for two items, but for the list [1, 2] it counts more. Which line is wrong?
def binary_insertion_count(values):
ranked = list(values)
count = 0
for i in range(1, len(ranked)):
x = ranked[i]
lo = 0
hi = len(ranked)
while lo < hi:
mid = lo + (hi - lo) // 2
count += 1
if ranked[mid] < x:
lo = mid + 1
else:
hi = mid
j = i
while j > lo:
ranked[j] = ranked[j - 1]
j -= 1
ranked[lo] = x
return countBinary insertion compares the next item with the middle of the ranked part, so every comparison rules out half of the window.
Exercise · Predict the output: Is a ranked list cheaper?. Binary insertion runs on the list that is already ranked: 1, 2, 3, 4. The code prints the comparisons made for each new item, and then the total. What does it print?
ranked = [1, 2, 3, 4]
counts = []
for i in range(1, len(ranked)):
x = ranked[i]
lo, hi = 0, i
count = 0
while lo < hi:
mid = lo + (hi - lo) // 2
count += 1
if ranked[mid] < x:
lo = mid + 1
else:
hi = mid
counts.append(count)
print(*counts, sum(counts))The two templates answer two different questions. You can choose between them before you write any code.
Then check the two ends: what does the count give for one item, and for two?
| Question | Answers to tell apart | Floor k |
|---|---|---|
| Rank 4 photos | 24 orders | 5 |
| Rank 10 photos | 3,628,800 orders | 22 |
| Rank 1,000 photos | 1,000! orders | 8,530 |
A contest has 6 finalists. The editors want the fewest comparisons any method could need to rank them all.
The answers to tell apart are the 6! = 720 orders. Template 1 doubles the endings until they reach 720.
| Comparisons k | Endings 2^k | Reaches 720? |
|---|---|---|
| 8 | 256 | no |
| 9 | 512 | no |
| 10 | 1,024 | yes |
The floor is 10 comparisons. Binary insertion needs at most 11 for 6 photos, as the table of sizes showed.
Real data brings edge cases.
With values = [31] there is one order, and 2^0 = 1 already covers it. The floor is 0, and binary insertion makes 0 comparisons: the loop over i never runs. A single item needs no comparison.
With values = [31, 12] there are 2 orders, and 2^1 = 2 covers them. One comparison is needed and enough. Binary insertion makes exactly 1 comparison, whichever order the two photos arrive in.
For values = [1, 2, 3, 4, 5, 6, 7, 8], binary insertion still makes 13 comparisons. It always halves the window, even when the new item belongs at the end. Linear insertion, which compares with the item before it, makes 7 comparisons on this list. Binary insertion saves comparisons in the worst case, but not on sorted input.
For n = 20, the 20! orders are 2,432,902,008,176,640,000, and the floor is 62 comparisons. For n = 21 the product is 51,090,942,171,709,440,000, which is more than the largest signed 64-bit integer, 9,223,372,036,854,775,807. Template 1 is exact only up to n = 20.
This version takes log2(n!) and drops the fraction. For three photos, log2(6) is 2.585, so it says 2 comparisons are enough.
Counterexample: a method that compares photo a with b, and then b with c, uses 2 comparisons. The score lists [1, 3, 2] and [2, 3, 1] both give the answers "a is below b" and "b is above c". The method cannot tell them apart, yet their sorted orders differ. Only 4 endings exist for 6 orders.
The fix is to round up. The count of endings must reach n!, never fall short of it.
Dropping the fraction says two comparisons rank three photos, but two comparisons give only four endings for six orders.
This version says "the floor for 1,000 photos is 8,530, so ranking any 1,000 photos takes at least 8,530 comparisons".
Counterexample: linear insertion on 1,000 photos that are already ranked makes 999 comparisons, far below 8,530. On the reverse order, the same method makes 499,500. The floor is a promise about the worst input: some input needs at least 8,530 comparisons from any method.
State the bound as a worst case. A lucky input can need far fewer.
This version computes the natural logarithm of n!, not the base-2 logarithm. Each comparison has two answers, so the base is 2.
Counterexample: ln(1,000!) is 5,912.1. Reading that as the number of comparisons says 5,913 are enough, yet 8,530 are needed, so the plan would be about 2,600 comparisons short. The base-2 logarithm of 1,000! is 8,529.4, which rounds up to 8,530.
Use base 2, because the questions are yes or no.
This version holds n! in a 32-bit integer, which Java and C++ use by default for int. The product passes 2,147,483,647 at n = 13.
Counterexample: 13! is 6,227,020,800, which wraps in 32 bits to 1,932,053,504. The floor computed from the wrapped number is 31 comparisons, but the correct floor for 13 items is 33.
Use a 64-bit integer up to n = 20, as the templates do, or a big-integer type, or a sum of logarithms for larger n.
A rewards screen in a payments app sorts 1,000,000 user ages, each a whole number from 0 to 120. The comparison floor for a million items is about 18,488,885 comparisons.
A counting sort never compares two ages. It adds 1 to a counter for each age, then reads the 121 counters in order. That takes about 1,000,121 steps, and the bound does not limit it, because it is not a comparison method. The model needs a method that learns only from comparisons.
Your team lead brings three product changes. Each one asks how many answers there are to tell apart.
A search tool has two ranked lists of 1,000 items each, and wants one ranked list. The orders to tell apart are no longer 2,000!. They are the ways to interleave the two lists, which is C(2000, 1000).
The floor is 1,995 comparisons, and a merge needs at most 1,999. The next lessons use this merge.
The contest wants only the winner, not the full ranking. The answers to tell apart are the 1,000 possible winners, so counting gives only ceil(log2 1,000) = 10. The real cost is 999 comparisons, because every photo except the winner must lose at least once. The counting rule is a floor, and a method may need more.
Exercise · Break it: Find the n where the counting rule is too low. This claims the fewest comparisons needed to find the strongest of n photos, by counting the possible winners. Find an n where the claim is too low.
def strongest_comparisons(n):
endings = 1
k = 0
while endings < n:
endings *= 2
k += 1
return kThe contest wants the runner-up too. A knockout tournament finds the winner in n − 1 comparisons, and the runner-up is among the photos that lost to the winner. Run on 8 photos it takes 9 comparisons, and on 16 photos it takes 18, which is n + ceil(log2 n) − 2.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why no comparison sort can rank n items in fewer than about n log n comparisons. Then say what the bound does not cover. 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.
A comparison has two answers, so k comparisons can end in at most 2^k ways. Sorting n items must tell n! orders apart, so 2^k has to be at least n!.
That makes k at least log2(n!), which grows like n log n. Binary insertion gets within a few comparisons of it.
The bound is for the worst case and for methods that only compare. Counting sort on small keys does not compare, so it can be faster.
The straightforward way to rank n items compares every pair, which costs n times n minus 1, over 2, comparisons. I can do much better, and I can also say how much better is possible.
Every comparison has two answers, so after k comparisons a method can end in at most 2 to the k different ways. Sorting n items must tell n factorial orders apart, so 2 to the k has to reach n factorial.
That means k is at least the base-2 logarithm of n factorial, which grows like n log n. For 1,000 items it is 8,530 comparisons, against 499,500 for every pair.
Binary insertion needs at most 8,977 comparisons for 1,000 items, and merge sort comes close too.
The bound is for the worst case, and only for methods that compare. Counting sort on small keys does not compare, so it can beat it.
Checkpoint · The counting rule
Q1/3 A comparison sort asks "is this item below that one?" about two items. What does each answer give the method?
Answer: B
A comparison has only two answers. After k comparisons a method can have at most 2^k different endings, which is what makes a lower bound possible.
Q2/3 A method has made 6 comparisons. At most how many different endings can it have?
Answer: C
Each comparison at most doubles the endings, so 6 comparisons give at most 2^6 = 64.
Q3/3 How many different orders can 5 items be in?
Answer: C
The first item can be any of 5, the next any of 4, and so on: 5 × 4 × 3 × 2 × 1 = 120.
Checkpoint · The floor
Q1/3 For 5 items there are 120 orders. What is the fewest comparisons any method can need in the worst case?
Answer: B
The endings must reach 120. 64 endings are too few and 128 are enough, so the smallest k is 7.
Q2/3 Why can no method rank 4 photos in 4 comparisons?
Answer: B
2^4 = 16 is below 4! = 24, so two different orders would share an ending, and the method would be wrong for one of them.
Q3/3 For 3 photos, log2(6) is 2.585. How many comparisons does the floor allow?
Answer: B
With 2 comparisons there are only 4 endings for 6 orders. The count must be a whole number that reaches n!, so the logarithm is rounded up.
Checkpoint · Using the model
Q1/2 Comparing every pair of 1,000 photos takes 499,500 comparisons. The floor is 8,530. About how many times as many comparisons does comparing every pair use?
Answer: B
499,500 divided by 8,530 is about 58.6, so roughly 60 times as many.
Q2/2 Linear insertion ranks a list of 1,000 photos that is already in order with 999 comparisons. The floor says 8,530. Does that break the floor?
Answer: B
The floor says that some input needs at least 8,530 comparisons from any method. It does not say that every input does.
Checkpoint · Where it stops
Q1/2 Which method is not limited by the comparison floor?
Answer: C
Counting sort reads each key as an index and never compares two items, so the model does not apply. The other three work by comparing.
Q2/2 To find only the strongest of 1,000 photos, counting the 1,000 possible winners gives a floor of 10. How many comparisons does finding the winner really need?
Answer: C
The counting floor is only a floor. Every photo except the winner needs a comparison that it loses, so n − 1 = 999 comparisons are needed.
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 | Sort and count the pickups that move | Rides | Easy | One sort, then compare with the original |
| 2 | Check whether a list is sorted | Ads | Easy | n − 1 comparisons are enough, and needed |
| 3 | Fewest comparisons for any batch size | Search | Medium | The counting rule as a sum of logarithms |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
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.