Counting sort and radix sort
Counting sort never compares: it counts each value and writes the values back in order, O(n + k) for k possible values; radix sort sorts digit by digit, ones, tens, hundreds, with a stable counting sort for each digit.
It can be proved that sorting only by "compare two numbers, which is bigger" needs at least log₂(n!) ≈ n log₂ n compares in the worst case. Merge sort and quicksort already reach that bound, and so does std::sort. To go faster you have to not compare: if you know the numbers are all integers from 0 to 99 (marks, ages, port numbers), just count how many there are of each value.
Counting sort: count, then write back
Make a vector<int> cnt(k, 0) (k is the range of values, k cells all 0): scan once, adding one to each value's count; then from small to large, write each value back as many times as it appeared.
i1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {3, 1, 4, 1, 3, 0};7 vector<int> cnt(5, 0);8 for (int x : a)9 cnt[x]++;10 int k = 0;11 for (int v = 0; v < 5; v++)12 while (cnt[v]-- > 0)13 a[k++] = v;14 for (int x : a)15 cout << x << " ";16 cout << "\n";17 return 0;18}
0 1 1 3 3 4
One scan is n, one walk through cnt is k: O(n + k), with O(k) extra space. A million marks from 0 to 100 take it a bit over two million steps, far fewer than quicksort's twenty million compares.
But it has conditions: the values are integers, and the range k can't be too big. If the values go from 0 to 10⁹, cnt needs 10⁹ ints, four billion bytes, which can't be allocated at all.
After counting it prints cnt[2] and "how many different values". What is it?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {2, 5, 2, 8, 5, 2};7 vector<int> cnt(10, 0);8 for (int x : a)9 cnt[x]++;10 int distinct = 0;11 for (int v = 0; v < 10; v++)12 if (cnt[v] > 0) distinct++;13 cout << cnt[2] << " " << distinct << "\n";14 return 0;15}
The values are all 0 to 2. After counting 2 0 2 1 0 2, what are cnt[0] cnt[1] cnt[2]?
Which data suits counting sort best?
Write counting sort
✓The values are all between 0 and 9. Finish the two steps: counting and writing back.
0 2 2 5 7 7 7 9
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {7, 2, 9, 2, 0, 7, 7, 5};7 vector<int> cnt(10, 0);8 // 1. add one to each value's cnt 2. from 0 to 9, write each value back cnt[v] times9 for (int x : a)10 cout << x << " ";11 cout << "\n";12 return 0;13}
The most common mark
✓The marks are all between 0 and 100. Use a count array to find the mark that appears most often (the smaller one on a tie), and print the mark and its count.
88 3
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> s = {88, 92, 75, 88, 60, 92, 88, 75, 100, 92};7 vector<int> cnt(101, 0);8 int best = 0;9 // count, then find the largest cnt from 0 to 10010 cout << best << " " << cnt[best] << "\n";11 return 0;12}
Radix sort: one digit at a time
When the range is large, go digit by digit: sort by the ones digit, then the tens, then the hundreds… Each digit has only ten kinds, 0 to 9, so use counting sort (the "stable" version here). Once the highest digit is sorted, the whole array is in order.
| Start | By ones | By tens | By hundreds |
|---|---|---|---|
| 170 | 170 | 802 | 2 |
| 45 | 90 | 2 | 24 |
| 75 | 802 | 24 | 45 |
| 90 | 2 | 45 | 66 |
| 802 | 24 | 66 | 75 |
| 24 | 45 | 170 | 90 |
| 2 | 75 | 75 | 170 |
| 66 | 66 | 90 | 802 |
Why doesn't sorting by tens after the ones mess up the order of the ones? Because every pass is stable: numbers with the same tens digit (802 and 2, say, both 0) keep the order the previous pass (by ones) gave them. So after the last pass, numbers whose high digits are equal are already in order by the low digits.
d digits, 10 kinds each: O(d × (n + 10)). A good fit for integers with a fixed number of digits and strings of equal length (sorted character by character). Decimals and objects compared by your own rule need a comparison sort.
After one (stable) pass by the ones digit, what does 31 12 22 41 13 become?
A million 6-digit student numbers, sorted by radix sort with 10 values per digit: about how many steps?
One pass: a stable counting sort
A stable counting sort no longer "writes the values straight back" after counting; it moves each item to where it belongs. First take prefix sums over cnt, so cnt[d] becomes "how many have a key ≤ d", which is one past where the last item with key d goes; then scan back to front and put each item at --cnt[key].
iEach pass of radix sort is one such counting sort, with "this digit" x / exp % 10 as the key:
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6void by_digit(vector<int>& a, int exp) {7 int n = a.size();8 vector<int> out(n), cnt(10, 0);9 for (int x : a) cnt[x / exp % 10]++;10 for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1]; // cnt[d]: how many have this digit ≤ d11 for (int i = n - 1; i >= 0; i--) // back to front: stays stable12 out[--cnt[a[i] / exp % 10]] = a[i];13 a = out;14}15 16int main() {17 vector<int> a = {170, 45, 75, 90, 802, 24, 2, 66};18 string names[] = {"by ones", "by tens", "by hundreds"};19 int exp = 1;20 for (int t = 0; t < 3; t++, exp *= 10) {21 by_digit(a, exp);22 cout << names[t] << ": ";23 for (int x : a) cout << x << " ";24 cout << "\n";25 }26 return 0;27}
by ones: 170 90 802 2 24 45 75 66 by tens: 802 2 24 45 66 170 75 90 by hundreds: 2 24 45 66 75 90 170 802
Two places in by_digit matter: the prefix sums turn cnt[d] into "how many have this digit ≤ d", exactly one past where the last of that group goes; and placing back to front is what keeps equal numbers in their original order. Front to back would not be stable, and the result would be wrong. At the end a = out; copies the whole vector back.
After counting, the program adds up running totals. What cnt does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {3, 1, 3, 0, 2};7 vector<int> cnt(4, 0);8 for (int x : a)9 cnt[x]++;10 for (int d = 1; d < 4; d++)11 cnt[d] += cnt[d - 1];12 for (int c : cnt)13 cout << c << " ";14 cout << "\n";15 return 0;16}
cnt[d] is "how many values are ≤ d": 1 2 3 5. So the two 3s go at indexes 3 and 4, and placing from the back, the later 3 goes in first, at index cnt[3] − 1 = 4.Each pass has to place the numbers into out from the back for the sort to be stable. Fill in where the loop starts so the program prints the sorted result.
1#include <iostream>2#include <vector>3using namespace std;4 5void by_digit(vector<int>& a, int exp) {6 int n = a.size();7 vector<int> out(n), cnt(10, 0);8 for (int x : a) cnt[x / exp % 10]++;9 for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];10 for (int i = ; i >= 0; i--)11 out[--cnt[a[i] / exp % 10]] = a[i];12 a = out;13}14 15int main() {16 vector<int> a = {329, 457, 657, 839, 436, 720, 355};17 for (int exp = 1; exp <= 100; exp *= 10)18 by_digit(a, exp);19 for (int x : a)20 cout << x << " ";21 cout << "\n";22 return 0;23}
n reads outside the array; starting at 0 runs the loop only once.These numbers have at most three digits. Change only the number in the green box so the program prints the fully sorted 329 355 436 457 657 720 839.
1#include <iostream>2#include <vector>3using namespace std;4 5void by_digit(vector<int>& a, int exp) {6 int n = a.size();7 vector<int> out(n), cnt(10, 0);8 for (int x : a) cnt[x / exp % 10]++;9 for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];10 for (int i = n - 1; i >= 0; i--)11 out[--cnt[a[i] / exp % 10]] = a[i];12 a = out;13}14 15int main() {16 vector<int> a = {329, 457, 657, 839, 436, 720, 355};17 for (int exp = 1; exp <= ; exp *= 10)18 by_digit(a, exp);19 for (int x : a)20 cout << x << " ";21 cout << "\n";22 return 0;23}
329 355 436 457 657 720 839
With the STL
The STL has no ready-made counting sort; sort is fast enough. But counting itself is used every day. When the size of cnt is only known at run time, vector<int> cnt(mx + 1, 0) fits; to know how many there are of one value only, use count from <algorithm>, which scans from start to end, O(n). When the range is large and sparse, count with a map<int, int> or unordered_map<int, int> instead (chapter 6).
When sorting, an element's "size" is decided by <: string compares in dictionary order character by character (capital letters have smaller codes than lowercase and come first), and pair compares first, and second only when first is equal. To sort by one key only and still keep equal ones in their original order, use stable_sort; it's merge sort, stable like counting sort.
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5#include <utility>6using namespace std;7 8int main() {9 vector<int> a = {3, 1, 4, 1, 3, 0};10 int mx = *max_element(a.begin(), a.end());11 vector<int> cnt(mx + 1, 0); // size known only at run time12 for (int x : a) cnt[x]++;13 cout << "1 appears " << cnt[1] << " times, count says " << count(a.begin(), a.end(), 1) << " too\n";14 15 vector<string> w = {"pear", "apple", "fig", "Banana", "app"};16 sort(w.begin(), w.end()); // dictionary order17 for (const string& s : w) cout << s << " ";18 cout << "\n";19 20 vector<pair<int, char>> p = {{3, 'e'}, {1, 'd'}, {2, 'c'}, {1, 'b'}, {3, 'a'}};21 vector<pair<int, char>> q = p;22 sort(p.begin(), p.end()); // first, then second23 stable_sort(q.begin(), q.end(), [](const pair<int, char>& x, const pair<int, char>& y) {24 return x.first < y.first; // first only25 });26 for (const pair<int, char>& x : p) cout << x.first << x.second << " ";27 cout << "\n";28 for (const pair<int, char>& x : q) cout << x.first << x.second << " ";29 cout << "\n";30 return 0;31}
1 appears 2 times, count says 2 too Banana app apple fig pear 1b 1d 2c 3a 3e 1d 1b 2c 3e 3a
"app" comes before "apple": the first three characters are equal, the shorter one runs out first, and that counts as smaller. sort puts 1b before 1d among the pairs because second takes part in the comparison too; stable_sort compares first only, so 1d and 1b, and 3e and 3a, keep their original order, the same order the stable counting sort above gives.
| Call | What it does | Cost |
|---|---|---|
vector<int> cnt(k, 0) + cnt[x]++ | Counting integers in a small range | O(n + k), O(k) space |
count(b, e, x) | How many of one value | O(n) each time; use cnt to count many values |
Counting with map<int, int> | Large, sparse range | O(log n) each |
sort on vector<string> | Dictionary order | O(n log n) compares, each up to O(length) |
sort on vector<pair> | first, then second | O(n log n) |
stable_sort(b, e, cmp) | Equal ones keep their order | O(n log n), O(n) extra space |
In interviews: "Is there a sort faster than O(n log n)?" Yes, but not a comparison sort. Counting sort is O(n + k) and radix sort O(d(n + b)), provided the keys are integers in a small range or can be split into digits. Common questions: "sort colours" (only the values 0, 1, 2, LeetCode 75), one counting pass and one writing pass; "the numbers are between 0 and n, sort in O(n)". Calling count for each value in a loop is a common O(n²) mistake: count once into a cnt first.
sort puts a vector<string> in dictionary order. What are the first two after sorting?
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int main() {8 vector<string> w = {"pear", "app", "Banana", "apple"};9 sort(w.begin(), w.end());10 cout << w[0] << " " << w[1] << "\n";11 return 0;12}
Summary
Sorting without comparing: counting and radix
- Counting: cnt[value]++, then write back smallest value first; O(n + k), k is the range, only for integers in a small range
- Stable version: prefix sums give the positions, place back to front
- Radix: lowest digit to highest, one stable counting sort per digit; O(d(n + 10))
- STL: count with vector<int> cnt or a map, count is O(n); pair compares first then second; stable_sort when you need stable
1vector<int> cnt(K, 0);2for (int x : a) cnt[x]++;3int k = 0;4for (int v = 0; v < K; v++)5 while (cnt[v]-- > 0) a[k++] = v;