Counting Sort
- Ω( n + k )
- Θ( n + k )
- O( n + k )
- space O( n + k )
Counting sort turns sorting into bookkeeping. It tallies how often each integer appears in a table indexed by the value itself, then walks the table from small to large and writes each value back as many times as it was counted. No two elements are ever compared to find their place; the only comparisons are the ones that locate the largest value so the table can be sized.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How counting sort works
On 5, 2, 6, 1, 4, 3 the scan for the maximum makes five comparisons and settles on 6, so the count table gets seven cells, for the values 0 to 6. The counting loop then reads each element once and adds one to its cell. All six values are different, so the table ends up with a 1 in cells 1 to 6 and a 0 in cell 0.
The write phase never reads the input again. It walks the table from cell 0, skips the empty cell, and writes 1 into index 0, giving 1, 2, 6, 1, 4, 3. Then 2 goes into index 1, which changes nothing because a 2 was already there. Then 3 goes into index 2 (1, 2, 3, 1, 4, 3), 4 into index 3, 5 into index 4 and 6 into index 5. The first row of the trace looks odd: the 5 that stood in index 0 has been overwritten, and the duplicate 1 is there because the original 1 at index 3 has not been reached yet.
Overwriting is safe because everything the sorted output needs now lives in the table. After counting, the input values are never consulted again. Six writes put the array in order, one per element, alongside 12 reads of the array (6 for the maximum scan, 6 for counting) and 13 reads and 6 writes on the table.
| Step | Change | Array after |
|---|---|---|
| 1 | Write 1 at index 0 | 1 2 6 1 4 3 |
| 2 | Write 2 at index 1 | 1 2 6 1 4 3 |
| 3 | Write 3 at index 2 | 1 2 3 1 4 3 |
| 4 | Write 4 at index 3 | 1 2 3 4 4 3 |
| 5 | Write 5 at index 4 | 1 2 3 4 5 3 |
| 6 | Write 6 at index 5 | 1 2 3 4 5 6 |
All 6 changes are shown.
Pseudocode
max = largest value in a
count[0 .. max] = 0
for each x in a
count[x] = count[x] + 1
k = 0
for v = 0 to max
repeat count[v] times
a[k] = v
k = k + 1
Why these complexities
Let k be the size of the table, here the maximum value plus one. The work is one scan to find the maximum (n − 1 comparisons), one scan to count, one sweep over k cells and n writes. Added up that is n + k for any order of the input, so best, average and worst coincide. There is no early exit and no input that does less.
The catch is k. It is set by the largest value, not by how many distinct values occur, so sorting 3, 1 and 9000 builds a table of 9001 cells for three elements. Counting sort wins when k is comparable to n or smaller, as with exam marks, ages or byte values, and loses badly when values are sparse over a wide range. Because it never compares elements to place them, it also escapes the n log n lower bound that applies to every comparison sort.
Space is the table, k cells. The n + k listed for this algorithm is the figure for the textbook version, which also fills an output array of n elements; this implementation skips that array because it writes plain numbers straight back into the input. The shortcut has a cost: it rewrites values from the counts instead of moving the original elements, so it cannot carry records along with their keys. That is why it is listed as not stable. The classic prefix-sum version, which moves each element to its running-total position, is stable, and that is the form radix sort builds on.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 31 | 64 | 0 |
| Already sorted | 31 | 64 | 0 |
| Reversed | 31 | 64 | 0 |
| Few distinct values | 31 | 64 | 0 |
When to use it
Use it for integers in a small known range, such as scores, ages or byte values, where it runs in linear time. It is a poor choice when the range of values is much larger than the number of elements.
Frequently asked questions
Why does it make so few comparisons?
It never compares elements to place them. It counts how often each value occurs, so the work shows up as reads and writes of the count table.
Can it sort negative numbers or strings?
Negative numbers work after shifting by the minimum. It suits only keys that map to a small range of integers.
Is counting sort stable?
The classic version with prefix sums is stable, which is why radix sort can build on it. For plain numbers, stability makes no visible difference.
What happens if one value is huge?
The table is sized by the maximum, so a single large value inflates both memory and the sweep over the table. Three elements 3, 1 and 9000 need 9001 cells and 9001 reads in the write phase. This implementation also assumes non-negative integers. In your own code, check the range first and fall back to a comparison sort when k is much larger than n.
How does it handle duplicate values?
A table cell simply holds a count above 1. For 2, 1, 2, 3 the table holds 0, 1, 2, 1 for the values 0 to 3, and the write phase writes the 2 twice in a row. Since only counts are kept, the order among equal numbers has no meaning here: they are indistinguishable anyway.
Background
Harold H. Seward described counting sort in 1954, in a master's thesis at MIT on sorting for electronic data processing, the same work that presents radix sort for computers. Knuth calls the technique distribution counting and gives it a place in the opening of section 5.2, ahead of the insertion, exchange and selection methods, a reminder that sorting does not have to rely on comparing keys.
Counting sort is the engine inside most radix sorts, and its stable form is the reason their digit passes compose correctly. It is used wherever the key range is small and fixed, such as sorting the characters of a string, building suffix arrays, or computing histograms of pixel values. Cormen, Leiserson, Rivest and Stein present it in chapter 8, Sorting in Linear Time, next to radix sort and bucket sort.
References
- Knuth, The Art of Computer Programming, vol. 3, section 5.2 (Internal Sorting), Algorithm D (distribution counting)
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, section 8.2 (Counting sort)
- Seward, Information Sorting in the Application of Electronic Digital Computers to Business Operations, MIT master's thesis, 1954
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Radix Sort | Θ( d(n + b) ) | O( d(n + b) ) |
| Bucket Sort | Θ( n + k ) | O( n2 ) |
| Best time | Ω( n + k ) | good |
|---|---|---|
| Average time | Θ( n + k ) | good |
| Worst time | O( n + k ) | good |
| Worst space | O( n + k ) | fair |
Properties
- Stable
- No
- In place
- No
- Adaptive
- No
- Comparison-based
- No