Kodewick
Start learning →
Counting sort and radix sort45 / 52

Counting sort and radix sort

Lesson 45 of 52 · Part 8 · Sorting · about 22 minutes

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.

a (left 6 cells) and cnt[0..4] (right 5 cells)acnt[0..4]3141300000001234567891011↑i

Counting 3 1 4 1 3 0: whatever the value is, add one to that cell of cnt; when the counting's done, write back from cnt, smallest first
main.cpp
1#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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

The values are all 0 to 2. After counting 2 0 2 1 0 2, what are cnt[0] cnt[1] cnt[2]?

Choose one

Which data suits counting sort best?

Exercise 1

Write counting sort

The values are all between 0 and 9. Finish the two steps: counting and writing back.

It should print
0 2 2 5 7 7 7 9
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter
Exercise 2

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.

It should print
88 3
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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.

ones0123456789

One pass by the ones digit: each number goes into the bucket of its ones digit, queuing behind the ones already there; then the buckets are emptied from 0 to 9
StartBy onesBy tensBy hundreds
1701708022
4590224
758022445
9024566
802246675
244517090
27575170
666690802

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.

Choose one

After one (stable) pass by the ones digit, what does 31 12 22 41 13 become?

Choose one

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].

a (left 5 cells) and out (right 5 cells)aout3a1b2c1d3e0123456789↑i

The key is the digit, the letter remembers the original order. cnt[1..3] = 2, 1, 2, after prefix sums 2, 3, 5; right to left, each item goes into out[--cnt[key]]

Each pass of radix sort is one such counting sort, with "this digit" x / exp % 10 as the key:

main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Fill inTap one to fill a blank; tap a blank to take it back

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}
Change it

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}
Should print
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.

main.cpp
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}
Output
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.

CallWhat it doesCost
vector<int> cnt(k, 0) + cnt[x]++Counting integers in a small rangeO(n + k), O(k) space
count(b, e, x)How many of one valueO(n) each time; use cnt to count many values
Counting with map<int, int>Large, sparse rangeO(log n) each
sort on vector<string>Dictionary orderO(n log n) compares, each up to O(length)
sort on vector<pair>first, then secondO(n log n)
stable_sort(b, e, cmp)Equal ones keep their orderO(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.

Guess the outputA wrong guess is fine

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

Take-away

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;