Sort small integer keys in linear time and keep equal items in order.
Use it when the keys are whole numbers in a small known range, or can be cut into small digits. Signal words: ratings, ages, scores, digits, fixed-width codes, equal keys keep their order.
Start one counter for each possible key, all zero.
Step count every key. Turn the counts into start places. Place each item, from left to right, at its key's free place and move that place up by 1. For radix sort, repeat this for each digit, from the last digit to the first.
Stop when every item is placed. For radix sort, stop after the digit of the largest value.
It does not compare keys, so it needs a small key range, and it needs a second list for the output.
Cost: O(n + k) time and space for n items and k possible keys. Radix sort costs O(d × (n + b)) for d digits in base b.
In this lesson you sort whole-number keys without comparing them, and you see why that can beat n log n. You learn what a stable sort is and why it matters. You then build radix sort, which sorts long keys one digit at a time, and you learn where linear-time sorting stops working.
You work on a music streaming app. A review page lists the plays of one popular playlist, each with a star rating from 1 to 5. The page shows 100,000 plays on every refresh, lowest rating first.
Plays with the same rating must stay in play order, because the team reads each rating group as a timeline.
Your team lead says: Sort the plays by rating on every refresh. You told me no comparison sort can beat n log n. Is that the end of it?
Here is a short test: eight plays, a to h, with ratings 4, 1, 3, 4, 2, 5, 1, 3. Sorted by rating, with equal ratings in play order, they read b, g, e, c, h, a, d, f.
So the task is this: order the plays by rating faster than n log n, and keep equal ratings in play order.
A post office has a rack of five pigeonholes, labelled 1 to 5. A clerk takes each parcel from the pile and drops it into the hole that matches its label. The clerk never compares one parcel with another.
When the pile is gone, the clerk empties hole 1, then hole 2, up to hole 5. The parcels in each hole are still in the order they arrived. The holes are the counters, and the label is the key.
A clerk drops each parcel into the pigeonhole that matches its label, and never compares one parcel with another.
Before you write code, count the eight ratings by hand. Keep one counter for each rating from 0 to 5.
Solve it by hand: Eight ratings: count them, then write them out. The hand-solve sheet loads in your browser.
You read each rating and add 1 to its counter. After all eight, the counters tell you how many plays each rating has. Then you write each rating out as many times as it was counted, from the smallest rating up.
The ratings are 4, 1, 3, 4, 2, 5, 1, 3. The counters are for the ratings 0, 1, 2, 3, 4 and 5.
| Rating read | Counters after |
|---|---|
| (start) | 0, 0, 0, 0, 0, 0 |
| 4 | 0, 0, 0, 0, 1, 0 |
| 1 | 0, 1, 0, 0, 1, 0 |
| 3 | 0, 1, 0, 1, 1, 0 |
| 4 | 0, 1, 0, 1, 2, 0 |
| 2 | 0, 1, 1, 1, 2, 0 |
| 5 | 0, 1, 1, 1, 2, 1 |
| 1 | 0, 2, 1, 1, 2, 1 |
| 3 | 0, 2, 1, 2, 2, 1 |
Writing each rating out as often as it was counted gives 1, 1, 2, 3, 3, 4, 4, 5. No two ratings were ever compared.
Start with a correct version. It sorts the ratings with a comparison sort and compares plays two at a time.
def sort_by_rating(plays):
# plays is a list of (rating, play_id); sorted() is stable, so equal ratings keep their order
return sorted(plays, key=lambda play: play[0])This is correct, and the sort is stable. On 100,000 plays it is also fast enough for one page. The team keeps it as the reference.
Now check the real size. The review service refreshes this page for every playlist, and a popular day has many of them.
Each refresh sorts 100,000 plays with ratings from 1 to 5.
Here is the count from a run:
So the comparison sort does about 7 times the work that the ratings need, and the gap grows with n.
Predict the cost
Q A list has 100,000 plays and ratings from 1 to 5. About how many steps does counting sort need to count and place them, with 6 counters?
Answer: C
Counting sort reads each play once to count it and once to place it, and it walks the 6 counters once. The total is 2n + k.
The first attempt is correct. But it asks a question about every pair of plays, when the keys only come in five kinds. The fix is to count the keys.
Look at the counters from the hand trace: 0, 2, 1, 2, 2, 1 for the ratings 0 to 5. They tell you something more than how many plays have each rating. They tell you where each rating starts in the sorted list.
Rating 1 has 2 plays, so rating 1 takes places 0 and 1. Rating 2 starts at place 2, because 2 plays come before it. Rating 3 starts at place 3. Rating 4 starts at place 5, and rating 5 starts at place 7.
Add the counters up as you go and you get the first place of each block: 0, 0, 2, 3, 5, 7. That running sum is called a prefix sum.
Now place each play at the next free place of its block. Read the plays from left to right. The first play with rating 4 goes to place 5, and the next one goes to place 6. Equal ratings fill their block in the order you read them.
Race: Merge sort and counting sort on star ratings. The operation counter loads in your browser.
The race counts steps by running both sorts on seeded random ratings from 1 to 5. At 1,000 plays merge sort made 8,204 comparisons and counting sort took 2,006 steps. At 100,000 plays the counts were 1,414,337 and 200,006.
Counting turns into start places. Each play goes to the next free place of its rating's block, read from left to right.
A sort is stable when items with equal keys keep their input order. Here the plays b and g both have rating 1, and b was played first. A stable sort puts b before g.
Counting sort is stable only because of the order of the last pass. It must read the plays from left to right. If it reads from right to left and fills each block from its start, g comes before b, and the sort is correct but not stable.
Dry run: The same plays, placed in input order. The step-by-step player loads in your browser.
The trace places the eight plays one at a time. Watch the first free place of each block move up by one after each play. The result is b, g, e, c, h, a, d, f, so equal ratings are in play order.
The ratings are 4, 1, 3, 4, 2, 5, 1, 3. The counters are 0, 2, 1, 2, 2, 1, so the first places of the blocks are 0, 0, 2, 3, 5, 7. The player stops three times and asks you for the place of a play.
Dry run: The same plays, placed in input order. The step-by-step player loads in your browser.
Reading without the player? Cover the last two columns and predict them row by row.
| Play | Rating | Goes to place | Free places of the blocks after it |
|---|---|---|---|
| a | 4 | 5 | 0, 0, 2, 3, 6, 7 |
| b | 1 | 0 | 0, 1, 2, 3, 6, 7 |
| c | 3 | 3 | 0, 1, 2, 4, 6, 7 |
| d | 4 | 6 | 0, 1, 2, 4, 7, 7 |
| e | 2 | 2 | 0, 1, 3, 4, 7, 7 |
| f | 5 | 7 | 0, 1, 3, 4, 7, 8 |
| g | 1 | 1 | 0, 2, 3, 4, 7, 8 |
| h | 3 | 4 | 0, 2, 3, 5, 7, 8 |
Every play went straight to its final place. Plays d and a, with rating 4, took places 6 and 5 in the order of reading: a first, then d.
Predict the place
Q The ratings are 4, 1, 3, 4, 2, 5, 1, 3, and the first places of the blocks are 0, 0, 2, 3, 5, 7. Play h has rating 3 and is read last. At which place does it go?
Answer: B
Rating 3 has the block of places 3 and 4. Play c is read first and takes place 3. Play h is read last and takes place 4.
Two passes over the plays and one over the counters are all it takes. No pair of plays is compared.
Exercise · Predict the output: Which indices does the placing pass print?. The code counts the keys, builds the start places, and places each index from left to right. The keys are 2, 0, 2, 1, 0. What does it print: the indices in their final order?
keys = [2, 0, 2, 1, 0]
limit = 3
counts = [0] * limit
for key in keys:
counts[key] += 1
starts = [0] * limit
total = 0
for key in range(limit):
starts[key] = total
total += counts[key]
order = [0] * len(keys)
for i, key in enumerate(keys):
order[starts[key]] = i
starts[key] += 1
print(*order)Here is the rule that keeps counting sort correct. Every line of the templates exists to protect it.
Counting sort turns key counts into start places, so each item goes to its final place, and a left-to-right pass keeps equal keys in order.
Before the placing pass, the first place of key k is the number of items with a smaller key. That is the final place of the first item with key k. Each item taken from the left raises its block's free place by 1, so the next item with the same key lands right after it.
That is why the sort is stable, and why a block never overflows. The counts say how many items a block holds, and the free place moves up once for each of them.
Use it when the keys are whole numbers in a small known range, or can be cut into small digits. Signal words: ratings, ages, scores, digits, fixed-width codes, equal keys keep their order.
Start: one counter for each possible key, all zero.
Step: count every key. Turn the counts into start places. Place each item, from left to right, at its key's free place and move that place up by 1. For radix sort, repeat this for each digit, from the last digit to the first.
Stop: when every item is placed. For radix sort, stop after the digit of the largest value.
It does not compare keys, so it needs a small key range, and it needs a second list for the output.
Cost: O(n + k) time and space for n items and k possible keys. Radix sort costs O(d × (n + b)) for d digits in base b.
def counting_sort(values, limit):
# [1] One counter for each possible key, all zero.
counts = [0] * limit
# [2] Count how many times each key occurs.
for value in values:
counts[value] += 1
# [3] Write each key out as many times as it was counted, from the smallest key up.
result = []
for key in range(limit):
result.extend([key] * counts[key])
return resultpublic int[] countingSort(int[] values, int limit) {
// [1] One counter for each possible key, all zero.
int[] counts = new int[limit];
// [2] Count how many times each key occurs.
for (int value : values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
int[] result = new int[values.length];
int place = 0;
for (int key = 0; key < limit; key++) {
for (int c = 0; c < counts[key]; c++) {
result[place++] = key;
}
}
return result;
}vector<int> countingSort(const vector<int>& values, int limit) {
// [1] One counter for each possible key, all zero.
vector<int> counts(limit, 0);
// [2] Count how many times each key occurs.
for (int value : values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
vector<int> result;
for (int key = 0; key < limit; key++) {
for (int c = 0; c < counts[key]; c++) {
result.push_back(key);
}
}
return result;
}function countingSort(values, limit) {
// [1] One counter for each possible key, all zero.
const counts = new Array(limit).fill(0);
// [2] Count how many times each key occurs.
for (const value of values) {
counts[value]++;
}
// [3] Write each key out as many times as it was counted, from the smallest key up.
const result = [];
for (let key = 0; key < limit; key++) {
for (let c = 0; c < counts[key]; c++) {
result.push(key);
}
}
return result;
}Exercise · Put it in order: Count, then write out. Arrange the lines into a counting sort that returns the values in order, from the smallest key up.
def counting_sort(values, limit):
counts = [0] * limit
result = []
for value in values:
counts[value] += 1
for key in range(limit):
for c in range(counts[key]):
result.append(key)
return result
counts = [0] * len(values)
counts[value] = 1This version only works for plain numbers, because it rebuilds each key from its counter. When the items are records with a key, you must move the records themselves. That needs start places.
def stable_order(keys, limit):
# [1] One counter for each possible key, then count the keys.
counts = [0] * limit
for key in keys:
counts[key] += 1
# [2] Turn the counts into start places: the first place for each key.
starts = [0] * limit
total = 0
for key in range(limit):
starts[key] = total
total += counts[key]
# [3] Place every index in input order, at its key's next free place.
order = [0] * len(keys)
for i, key in enumerate(keys):
order[starts[key]] = i
starts[key] += 1
# [4] Return the order of original indices.
return orderpublic int[] stableOrder(int[] keys, int limit) {
// [1] One counter for each possible key, then count the keys.
int[] counts = new int[limit];
for (int key : keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
int[] starts = new int[limit];
int total = 0;
for (int key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
int[] order = new int[keys.length];
for (int i = 0; i < keys.length; i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}vector<int> stableOrder(const vector<int>& keys, int limit) {
// [1] One counter for each possible key, then count the keys.
vector<int> counts(limit, 0);
for (int key : keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
vector<int> starts(limit, 0);
int total = 0;
for (int key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
vector<int> order(keys.size());
for (int i = 0; i < (int)keys.size(); i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}function stableOrder(keys, limit) {
// [1] One counter for each possible key, then count the keys.
const counts = new Array(limit).fill(0);
for (const key of keys) {
counts[key]++;
}
// [2] Turn the counts into start places: the first place for each key.
const starts = new Array(limit).fill(0);
let total = 0;
for (let key = 0; key < limit; key++) {
starts[key] = total;
total += counts[key];
}
// [3] Place every index in input order, at its key's next free place.
const order = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
order[starts[keys[i]]] = i;
starts[keys[i]]++;
}
// [4] Return the order of original indices.
return order;
}Exercise · Find the bug: The start places that restart. This stable counting sort should return the indices in key order, but for the keys [1, 1, 2, 0] it returns an index twice. Which line is wrong?
def stable_order(keys, limit):
counts = [0] * limit
for key in keys:
counts[key] += 1
starts = [0] * limit
total = 0
for key in range(limit):
starts[key] = total
total = counts[key]
order = [0] * len(keys)
for i, key in enumerate(keys):
order[starts[key]] = i
starts[key] += 1
return orderRadix sort handles keys that are too large to count at once. It cuts each key into digits and runs a stable counting sort on each digit, starting with the last digit. The template takes whole numbers from 0 up; shift negative keys first, as the edge cases below show.
def radix_sort(values):
items = list(values)
if not items:
return items
# [1] The number of passes is the number of digits of the largest value.
biggest = max(items)
place = 1
while biggest // place > 0:
# [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
counts = [0] * 10
for value in items:
counts[(value // place) % 10] += 1
starts = [0] * 10
total = 0
for digit in range(10):
starts[digit] = total
total += counts[digit]
result = [0] * len(items)
for value in items:
digit = (value // place) % 10
result[starts[digit]] = value
starts[digit] += 1
items = result
# [3] Move to the next higher digit.
place *= 10
# [4] Return the sorted values.
return itemspublic int[] radixSort(int[] values) {
int[] items = values.clone();
if (items.length == 0) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
int biggest = 0;
for (int value : items) {
biggest = Math.max(biggest, value);
}
long place = 1;
while (biggest / place > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
int[] counts = new int[10];
for (int value : items) {
counts[(int) ((value / place) % 10)]++;
}
int[] starts = new int[10];
int total = 0;
for (int digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
int[] result = new int[items.length];
for (int value : items) {
int digit = (int) ((value / place) % 10);
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}vector<int> radixSort(const vector<int>& values) {
vector<int> items = values;
if (items.empty()) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
int biggest = *max_element(items.begin(), items.end());
long long place = 1;
while (biggest / place > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
vector<int> counts(10, 0);
for (int value : items) {
counts[(value / place) % 10]++;
}
vector<int> starts(10, 0);
int total = 0;
for (int digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
vector<int> result(items.size());
for (int value : items) {
int digit = (value / place) % 10;
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}function radixSort(values) {
let items = [...values];
if (items.length === 0) {
return items;
}
// [1] The number of passes is the number of digits of the largest value.
const biggest = Math.max(...items);
let place = 1;
while (Math.floor(biggest / place) > 0) {
// [2] Sort by this digit with a stable counting sort, so earlier passes survive on ties.
const counts = new Array(10).fill(0);
for (const value of items) {
counts[Math.floor(value / place) % 10]++;
}
const starts = new Array(10).fill(0);
let total = 0;
for (let digit = 0; digit < 10; digit++) {
starts[digit] = total;
total += counts[digit];
}
const result = new Array(items.length);
for (const value of items) {
const digit = Math.floor(value / place) % 10;
result[starts[digit]] = value;
starts[digit]++;
}
items = result;
// [3] Move to the next higher digit.
place *= 10;
}
// [4] Return the sorted values.
return items;
}Rebuild the template: put its lines back in order. Loads in your browser.
Radix sort runs a stable counting pass for each digit, from the last digit to the first.
Exercise · Break it: Find the values that need more passes. This radix sort runs exactly three stable passes, because the example codes have 3 digits. The values are whole numbers from 0 up. Find a list that it leaves unsorted.
def radix_sort(values):
items = list(values)
place = 1
for _ in range(3):
counts = [0] * 10
for value in items:
counts[value // place % 10] += 1
starts = [0] * 10
for digit in range(1, 10):
starts[digit] = starts[digit - 1] + counts[digit - 1]
result = [0] * len(items)
for value in items:
digit = value // place % 10
result[starts[digit]] = value
starts[digit] += 1
items = result
place *= 10
return itemsThe three templates share one question: can the keys be counted? You can answer it before you write code.
Then check the two ends: what do the templates do on an empty list, and when every key is equal?
| Situation | Use | Why |
|---|---|---|
| Ratings 1 to 5, 100,000 items | Counting sort | 2n + 6 steps |
| Equal keys must keep their order | Stable counting, left to right | The free place moves up once for each item |
| Keys up to 10^9, fixed width | Radix sort | A few passes of 10 or 256 counters |
| Keys up to 10^9, only 1,000 items | A comparison sort | 4-byte counters would take 4,000,000,004 bytes |
The app counts how often listeners skip each of seven tracks in the first minute: 2, 0, 3, 0, 1, 3 and 0. The skips are keys from 0 to 3, and you want the tracks in order of skips, with equal skips in track order.
Template 2 counts the keys: 3, 1, 1 and 2 for the keys 0 to 3. The start places are 0, 3, 4 and 5.
| Track | Skips | Goes to place | Free place of its block after |
|---|---|---|---|
| 0 | 2 | 4 | 5 |
| 1 | 0 | 0 | 1 |
| 2 | 3 | 5 | 6 |
| 3 | 0 | 1 | 2 |
| 4 | 1 | 3 | 4 |
| 5 | 3 | 6 | 7 |
| 6 | 0 | 2 | 3 |
The order of tracks is 1, 3, 6, 4, 0, 2, 5. The three tracks with 0 skips come first, in track order 1, 3, 6.
Real data brings edge cases.
For values = [] or one item, every loop runs zero times or once. The templates return the list as it is. Radix sort checks for an empty list first, because it calls the largest value.
For keys = [2, 2, 2] the block of key 2 holds all three items. Template 2 returns the order 0, 1, 2, so equal keys keep their input order. Counting sort does the same work as on any other input: 2n + k steps.
For values = [0, 0, 5, 5] with limit = 6, keys 0 and 5 sit at the first and last counter. Both templates handle them. A key equal to limit would write past the array, so limit must be the largest key plus 1.
For values = [-3, 5, -1, 0, 5, -3] a counter cannot sit at index -3. Subtract the smallest value, -3, from every key. The shifted keys are 0, 8, 2, 3, 8 and 0, which need 9 counters. Add the shift back when you write the keys out.
This version reads the plays from the last to the first and fills each block from its start. The order is sorted by rating, but equal ratings are reversed.
Counterexample: the eight plays with ratings 4, 1, 3, 4, 2, 5, 1, 3 come out as g, b, e, h, c, d, a, f. Plays b and g, both rated 1, swapped places. The stable result is b, g, e, c, h, a, d, f.
Read from left to right when you place, or fill each block from its end while reading from right to left.
This version makes the counter array as long as the number of items, because "n counters is enough".
Counterexample: for values = [7, 3, 9] the array has 3 counters, and reading key 7 raises IndexError in Python. The array must hold one counter for every possible key, so it needs the largest key plus 1 counters.
Size the counters by the key range, not by n.
Reading the plays from right to left reverses each block: g comes before b, though b was played first.
This version runs the stable passes from the first digit to the last. The last pass then decides the whole order.
Counterexample: for [21, 12] the pass on the tens gives 12, 21, and the pass on the units gives 21, 12. The list is not sorted. The correct order is 12, 21.
Run the passes from the last digit to the first, so the most significant digit has the last word.
This version uses the right-to-left placing of Exhibit 1 for each digit. A pass then reverses items whose digit is equal, and it destroys the work of earlier passes.
Counterexample: for [12, 15, 11, 10] the pass on the last digit gives 10, 11, 12, 15. The pass on the tens digit finds four equal digits and reverses them: 15, 12, 11, 10. The correct result is 10, 11, 12, 15.
Every pass must be stable.
A review service sorts 1,000 account numbers, each up to 10^9. A counting sort needs 1,000,000,001 counters, which is 4,000,000,004 bytes at 4 bytes each. Merge sort on 1,000 random distinct numbers made 8,717 comparisons.
Radix sort fits the memory, with 10 passes of 10 counters, but it is still more work than the list needs. Use a comparison sort here.
Your team lead brings four product changes. Each one changes what the keys are.
The page needs the index of each play in rating order, not the ratings themselves. That is Template 2 exactly. The problem "Count sort of small scores" practises it, with equal scores kept in input order.
Track codes have six digits, and the page sorts them after each batch. Radix sort makes six stable passes, one for each digit. The problem "Radix order of fixed width codes" asks for the list after a given number of passes.
The team lists tracks by how many plays they have. The counts are themselves small whole numbers, between 1 and n, so a counting sort over the counts orders the tracks. LeetCode 347: Top K Frequent Elements uses this bucket idea.
The team needs the largest gap between neighbours in the sorted play times, without a comparison sort. Putting the values into buckets whose width is the average gap gives a linear answer. This is LeetCode 164: Maximum Gap.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how counting sort works and why it can be faster than n log n. Then say what stable means and why radix sort needs it. 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.
Counting sort counts how many items have each key, turns the counts into start places, and puts each item straight into its place. It never compares two items, so it costs O(n + k) for k possible keys. I place from left to right, so the sort is stable. Radix sort runs one stable pass for each digit, last digit first, and needs a key range that is small next to n.
When keys are whole numbers in a small range, I do not compare. I count how many items have each key, turn the counts into start places with a running sum, and place each item in its block. That costs O(n plus k) time and space, for k possible keys.
I place from left to right, so the sort is stable: equal keys keep their input order. That matters when the items are records, and it is what makes radix sort work. Radix sort runs a stable counting pass on each digit, from the last digit to the first. Each pass keeps the order that the earlier passes made, so the most significant digit has the last word.
The limit is the key range. For 100,000 ratings from 1 to 5, counting took 200,006 steps and merge sort took 1,414,337 comparisons. For 1,000 keys up to a billion, 4-byte counters alone would need 4,000,000,004 bytes, so I use a comparison sort there.
Checkpoint · Counting sort and stability
Q1/10 How does counting sort put whole-number keys in order?
Answer: B
Counting sort never compares two keys. It counts the keys and turns the counts into places, so the n log n bound for comparison sorts does not apply.
Q2/10 A list has 100,000 plays with ratings from 1 to 5, and the sort uses 6 counters. How many steps does counting sort take: one to count and one to place each play, plus one for each counter?
Answer: C
The sort counts each play once, places each play once, and walks 6 counters once: 2 × 100,000 + 6 = 200,006. The figure 1,414,337 is what a merge sort counted on the same size of list.
Q3/10 The counters for the ratings 0 to 5 are 0, 2, 1, 2, 2, 1. What are the first places of the blocks?
Answer: B
The first place of a key is the number of items with a smaller key: a running sum of the counters, starting at 0. So the places are 0, 0, 2, 3, 5, 7.
Q4/10 What does it mean when a sort is stable?
Answer: C
Stability is about items with equal keys. If two plays both have rating 1, the one played first stays first.
Q5/10 Which way must you read the items in the placing pass for counting sort to be stable, when each block is filled from its start?
Answer: B
Reading from left to right fills each block in input order. The lesson ran the opposite order and got g before b for two plays that both had rating 1.
Q6/10 The placing pass reads plays a to h from right to left and fills each block from its start. The ratings are 4, 1, 3, 4, 2, 5, 1, 3. What is the order of the plays?
Answer: B
The ratings are still sorted, but each block is reversed. The correct stable order is b, g, e, c, h, a, d, f, and the reversed blocks give g, b, e, h, c, d, a, f.
Q7/10 In radix sort on three-digit codes, which digit does the first pass sort by?
Answer: B
Radix sort goes from the last digit to the first. The first digit is sorted last, so it has the last word. Going the other way sorted [21, 12] into 21, 12.
Q8/10 The codes are 329, 457, 657, 839, 436, 720 and 355. What is the list after the first pass, a stable sort by the last digit?
Answer: C
The last digits are 9, 7, 7, 9, 6, 0 and 5. In order they give 720 (0), 355 (5), 436 (6), then 457 and 657 (7, in input order), then 329 and 839 (9).
Q9/10 A service sorts 1,000 account numbers, each up to 10^9. Why is a counting sort a poor choice?
Answer: C
Memory and time grow with the key range. With 4-byte counters, 10^9 + 1 counters need 4,000,000,004 bytes, far more than the 1,000 numbers need.
Q10/10 Equal records must keep their order, and you want an O(n log n) comparison sort. Which one do you pick?
Answer: B
Merge sort is stable. The quick sort of the last lesson swapped equal records, and selection sort written with swaps is not stable either.
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 ages in linear time | Feed | Easy | Counting sort on keys in a small range |
| 2 | Count sort of small scores | Search | Easy | A stable order of indices from start places |
| 3 | Radix order of fixed width codes | Maps | Medium | Stable passes, last digit first |
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.