Algorithm Deep Dives

Counting Sort Explained

Counting Sort sorts integers in O(n + k) linear time without comparisons. Learn how it works, when it beats Quick Sort, and its memory trade-offs.

Aman Jaiman
5 min read
On this page +
  1. In plain English
  2. How Counting Sort works
  3. Why it beats O(n log n)
  4. The catch: memory and range
  5. Frequently asked questions

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.

Found this useful?

Share it with someone who is learning this too.

Questions

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 nine others run step by step, with live pseudocode and comparison counters.

Launch the visualiser
Aman Jaiman
Written by
Aman Jaiman

Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.

Keep reading

Related guides

Link copied