sort.cny.shStart a race
Back to library
11 / 18Algorithm

Counting Sort

Tally each value, then fill the array back in order.

StableIn-place
BestO(n + k)
AverageO(n + k)
WorstO(n + k)
01How it works

Count how many times each key value occurs, turn the counts into a prefix sum, then place each input element directly at its final index. One scan to count, one to place — no comparisons involved.

02Best for

Integer keys drawn from a small known range — grading curves, histogramming, pixel intensities, bucket step inside radix sort. Linear in n + k and naturally stable.

03Avoid when

The key range k dwarfs the array size n. You end up allocating and scanning an enormous counts array for very little actual work.