Counting sort
A sorting algorithm that doesn't compare: it counts how many times each value appears and writes them in order. It works for integers in a small range.
Example
With 1 million grades from 1 to 10, it counts how many 1s, how many 2s... and writes them out: about 1 million steps.
Test yourself: Counting sort
Counting sort
To sort [3, 1, 3, 0], the counters array becomes [1, 1, 0, ___].
There's 1 zero, 1 one, 0 twos and 2 threes. Writing in order: [0, 1, 3, 3].
Counting sort
With counters [1, 2, 1] for values 0, 1 and 2, the prefix sums are [1, 3, ___].
1, 1 + 2 = 3, 3 + 1 = 4. They say the last 0 goes at index 0, the last 1 at 2 and the 2 at 3.
Counting sort
Counting sort costs O(n + ___), where m is the maximum value.
With 1 million ages from 0 to 120: 1 million steps for the data and 121 for the counters.
0/3
â–¶ Play