Kodewick
Start learning →
Counting sort and radix sort43 / 50

Counting sort and radix sort

Lesson 43 of 50 · Part 8 · Sorting · about 15 minutes

Counting sort doesn't compare: it counts each value with cnt[a[i]]++ and writes them back in order, O(n + k) for values in a range of k, and radix sort sorts one digit at a time, ones first, with a stable counting sort for each digit.

It can be proved that sorting by comparing pairs alone takes, at worst, at least log₂(n!) ≈ n log₂ n comparisons. Merge sort and quicksort already reach that limit. To go faster you have to not compare: if you know the values are whole numbers from 0 to 99 (scores, ages, port numbers), you can just count how many there are of each.

Counting sort: count, then write back

Make an array cnt[k] (k is the range of values): one pass adds one to each value's count; then, from small to large, each value is written back as many times as it appeared.

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

Counting 3 1 4 1 3 0: whatever the value is, add one to that slot of cnt
main.c
1#include <stdio.h>2 3int main(void) {4    int a[] = {3, 1, 4, 1, 3, 0};5    int n = 6, cnt[5] = {0};6    for (int i = 0; i < n; i++)7        cnt[a[i]]++;8    int k = 0;9    for (int v = 0; v < 5; v++)10        while (cnt[v]-- > 0)11            a[k++] = v;12    for (int i = 0; i < n; i++)13        printf("%d ", a[i]);14    printf("\n");15    return 0;16}
Output
0 1 1 3 3 4 

One pass over the n numbers, one over cnt's k slots: O(n + k), with O(k) extra space. A million scores from 0 to 100 take about two million steps, far fewer than quicksort's twenty million comparisons.

But it has conditions: whole numbers, in a range k that isn't too big. Values from 0 to 10⁹ would need a cnt array of 4 billion bytes, which can't be had.

Guess the outputA wrong guess is fine

After counting it prints cnt[2] and "how many different values". What?

1#include <stdio.h>2 3int main(void) {4    int a[] = {2, 5, 2, 8, 5, 2};5    int cnt[10] = {0};6    for (int i = 0; i < 6; i++)7        cnt[a[i]]++;8    int distinct = 0;9    for (int v = 0; v < 10; v++)10        if (cnt[v] > 0) distinct++;11    printf("%d %d\n", cnt[2], distinct);12    return 0;13}
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 0 to 9. Finish the two steps: counting, then writing back.

It should print
0 2 2 5 7 7 7 9
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int a[] = {7, 2, 9, 2, 0, 7, 7, 5};5    int n = 8, cnt[10] = {0};6    // 1. add one to each value's cnt  2. from 0 to 9, write each value back cnt[v] times7    for (int i = 0; i < n; i++)8        printf("%d ", a[i]);9    printf("\n");10    return 0;11}
Output
Press Run or Ctrl+Enter
Exercise 2

The most common score

Scores are 0 to 100. With a count array, find the score that appears most often (the smaller on a tie), and print it with its count.

It should print
88 3
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int s[] = {88, 92, 75, 88, 60, 92, 88, 75, 100, 92};5    int n = 10, cnt[101] = {0};6    int best = 0;7    // count, then find the largest cnt from 0 to 1008    printf("%d %d\n", best, cnt[best]);9    return 0;10}
Output
Press Run or Ctrl+Enter

Radix sort: one digit at a time

When the range is large, sort by digit: by the ones digit first, then the tens, then the hundreds… Each digit has only ten values, 0 to 9, so each pass is a counting sort (the "stable" version). After the highest digit, the whole array is sorted.

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 undo the order by ones? Because every pass is stable: numbers with the same tens digit (802 and 2, both 0) keep the order the previous pass (by ones) left them in. So after the last pass, numbers with the same high digits are already in order by the lower ones.

d digits of 10 values each: O(d × (n + 10)). It suits whole numbers of fixed length, and strings (one character at a time).

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

Each pass of radix sort sorts the whole numbers by one of their digits. Counting how many there are and writing the values back, as counting sort does, won't do here: it is the whole numbers that have to move, and numbers with the same digit must keep the order the previous pass left them in. by_digit is one such pass; with exp = 1 it looks at the ones digit, with 10 at the tens, with 100 at the hundreds:

main.c
1#include <stdio.h>2 3void by_digit(int a[], int n, int exp) {4    int out[16], cnt[10] = {0};5    for (int i = 0; i < n; i++) cnt[a[i] / exp % 10]++;6    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];      // cnt[d]: how many have this digit ≤ d7    for (int i = n - 1; i >= 0; i--)                       // placed from the back: stays stable8        out[--cnt[a[i] / exp % 10]] = a[i];9    for (int i = 0; i < n; i++) a[i] = out[i];10}11 12int main(void) {13    int a[] = {170, 45, 75, 90, 802, 24, 2, 66};14    int n = 8;15    for (int exp = 1; exp <= 100; exp *= 10) {16        by_digit(a, n, exp);17        printf("by %3d: ", exp);18        for (int i = 0; i < n; i++) printf("%d ", a[i]);19        printf("\n");20    }21    return 0;22}
Output
by   1: 170 90 802 2 24 45 75 66 
by  10: 802 2 24 45 66 170 75 90 
by 100: 2 24 45 66 75 90 170 802 

Note two things in by_digit: the running total makes cnt[d] "how many have this digit ≤ d", exactly where the last of that group goes; and placing from the back keeps equal digits in their earlier order. Place from the front and it isn't stable, and the result is wrong.

Guess the outputA wrong guess is fine

After counting, the program adds up running totals. What cnt does it print?

1#include <stdio.h>2 3int main(void) {4    int a[] = {3, 1, 3, 0, 2};5    int cnt[4] = {0};6    for (int i = 0; i < 5; i++)7        cnt[a[i]]++;8    for (int d = 1; d < 4; d++)9        cnt[d] += cnt[d - 1];10    for (int d = 0; d < 4; d++)11        printf("%d ", cnt[d]);12    printf("\n");13    return 0;14}
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 <stdio.h>2 3void by_digit(int a[], int n, int exp) {4    int out[16], cnt[10] = {0};5    for (int i = 0; i < n; i++) cnt[a[i] / exp % 10]++;6    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];7    for (int i = ; i >= 0; i--)8        out[--cnt[a[i] / exp % 10]] = a[i];9    for (int i = 0; i < n; i++) a[i] = out[i];10}11 12int main(void) {13    int a[] = {329, 457, 657, 839, 436, 720, 355};14    int n = 7;15    for (int exp = 1; exp <= 100; exp *= 10)16        by_digit(a, n, exp);17    for (int i = 0; i < n; i++)18        printf("%d ", a[i]);19    printf("\n");20    return 0;21}
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 <stdio.h>2 3void by_digit(int a[], int n, int exp) {4    int out[16], cnt[10] = {0};5    for (int i = 0; i < n; i++) cnt[a[i] / exp % 10]++;6    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];7    for (int i = n - 1; i >= 0; i--)8        out[--cnt[a[i] / exp % 10]] = a[i];9    for (int i = 0; i < n; i++) a[i] = out[i];10}11 12int main(void) {13    int a[] = {329, 457, 657, 839, 436, 720, 355};14    int n = 7;15    for (int exp = 1; exp <= ; exp *= 10)16        by_digit(a, n, exp);17    for (int i = 0; i < n; i++)18        printf("%d ", a[i]);19    printf("\n");20    return 0;21}
Should print
329 355 436 457 657 720 839

Summary

Take-away

Sorting without comparing: counting and radix

  • Counting: cnt[value]++, then write back by value, smallest first; O(n + k), k the range
  • Only for whole numbers in a small range
  • Radix: low digit to high, one stable counting sort per digit; O(d(n + 10))
  • Each pass must be stable: place from the back
1for (i = 0; i < n; i++) cnt[a[i]]++;2for (v = 0, k = 0; v < K; v++)3    while (cnt[v]-- > 0) a[k++] = v;