Algorithm Deep Dives

Counting Sort Explained

Updated June 8, 2026 5 min read

Counting Sort is a non-comparison algorithm that sorts integers in linear O(n + k) time, where k is the range of values. Instead of comparing elements, it counts how many times each value appears and uses those counts to place every element directly into its final position.

How Counting Sort works

First, count occurrences of each value into a count array indexed by value. Then compute a running (prefix) sum so each entry tells you the final position of that value. Finally, walk the input from right to left, placing each element at its computed position and decrementing the count — which keeps the sort stable.

Why it beats O(n log n)

Counting Sort never compares two elements, so the comparison-sort lower bound does not apply to it. For data like exam scores (0-100) or ages, where k is small, it sorts in true linear time — far faster than Quick or Merge Sort.

The catch: memory and range

Counting Sort needs O(k) memory for the count array. If you have 100 values ranging up to 10 million, you would allocate 10 million slots — wasteful and slow. It only works on integers (or data mappable to integers) with a modest range. For larger ranges, Radix Sort applies Counting Sort digit by digit to keep k small.

Frequently asked questions

What is the time complexity of Counting Sort? +
O(n + k), where n is the number of elements and k is the range of input values. It uses O(k) extra space and is stable.
When should you use Counting Sort? +
When sorting integers (or integer-mappable keys) with a small, known range relative to n — for example scores, ages, or small categorical IDs.
Why isn't Counting Sort used everywhere if it's O(n)? +
Because it needs O(k) memory and only works on bounded integers. With a huge value range it becomes impractical, so comparison sorts remain the general-purpose default.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles