Counting Sort
Software Engineer path · lesson 14 of 99A non-comparison sorting algorithm that achieves O(n+k) time by counting occurrences. Perfect when the range of values (k) is not significantly larger than n.
Whole numbers 0–20. Counting sort pays for the range k, so try Wide range and watch the count array grow.
Values range 0..8, so make 9 counters. No comparisons at all.
- 1count = [0] * (k+1)
- 2for x in a: count[x] += 1
- 3for v in 1..k: count[v] += count[v-1] # end positions
- 4for x in reversed(a): # reversed keeps it stable
- 5 count[x] -= 1
- 6 out[count[x]] = x
- Reads
- 0 / 14
- Writes
- 0 / 22
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Sort without comparing
Order the steps of a stable counting sort.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
When is Counting Sort most efficient?
The short version
Imagine sorting a deck of cards by suit. Instead of comparing cards, you count how many of each suit you have, then deal them out in order. No comparisons needed!
In more depth
Three Phases
1. Count Phase: Count occurrences of each value
2. Cumulative Phase: Convert counts to positions
3. Output Phase: Place elements in correct positions
Stability
Iterating backwards during output phase ensures stability (equal elements maintain relative order).
Limitations
When to reach for this
- Values are integers in a known, limited range
- Need linear O(n) sorting
- Sorting characters, grades, or small integers
- As a subroutine in Radix Sort
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required