Counting Sort in Data Structure
Counting Sort is a non-comparison-based sorting algorithm that counts the number of occurrences of each distinct value in the input, then uses those counts to place elements directly into their sorted position.
Algorithm Steps
- Find the range of input values (minimum and maximum).
- Create a count array to store the frequency of each value.
- Transform the count array so each element holds the cumulative count (sum of previous counts).
- Place each input element into the output array based on its cumulative count, then decrement the count.
def counting_sort(arr):
if not arr:
return arr
max_val = max(arr)
count = [0] * (max_val + 1)
for num in arr:
count[num] += 1
for i in range(1, len(count)):
count[i] += count[i - 1]
output = [0] * len(arr)
for num in reversed(arr):
count[num] -= 1
output[count[num]] = num
return output
Complexity
| Metric | Value |
|---|---|
| Time | O(n + k) |
| Space | O(n + k) |
Here n is the number of elements and k is the range of input values. Counting Sort is efficient only when k is not significantly larger than n.
Applications
- Sorting grades, ages, or other bounded-range integer data.
- Used as a subroutine within Radix Sort.
- Frequency-based data analysis.
Dry Run With Cumulative Counts
Let's sort [4, 2, 2, 8, 3, 3, 1] by hand. The largest value is 8, so the count array has positions 0 to 8.
| Value (index) | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| Frequency | 0 | 1 | 2 | 2 | 1 | 0 | 0 | 0 | 1 |
| Cumulative | 0 | 1 | 3 | 5 | 6 | 6 | 6 | 6 | 7 |
The cumulative value tells you where a value's block ends in the output. Value 3 has cumulative count 5, so the two 3s occupy output positions 3 and 4. Now walk the input from right to left:
- 1: count becomes 0, place at index 0.
- 3 (the last one): count becomes 4, place at index 4.
- 3 (the earlier one): count becomes 3, place at index 3.
- 8: count becomes 6, place at index 6.
- 2, then 2: placed at indices 2 and 1.
- 4: count becomes 5, place at index 5.
The output is [1, 2, 2, 3, 3, 4, 8].
Why Walking Backwards Keeps It Stable
The last 3 in the input fills the last slot reserved for 3s, and the earlier 3 fills the slot before it. So equal values come out in their original order. With plain numbers you cannot see the difference, but it matters when you sort records by a key, and it is the reason counting sort can be used inside radix sort.
students = [("Asha", 2), ("Ravi", 1), ("Neha", 2), ("Karan", 0)]
def sort_by_grade(records, max_key):
count = [0] * (max_key + 1)
for _, g in records:
count[g] += 1
for i in range(1, len(count)):
count[i] += count[i - 1]
out = [None] * len(records)
for rec in reversed(records):
count[rec[1]] -= 1
out[count[rec[1]]] = rec
return out
print(sort_by_grade(students, 2))
# [('Karan', 0), ('Ravi', 1), ('Asha', 2), ('Neha', 2)]
Asha stays ahead of Neha because she appeared first in the input.
Supporting Negative Numbers With an Offset
The basic version uses the value itself as an index, so negatives break it. Shift every value by the minimum so the smallest one maps to index 0. This also saves memory when values start far from zero, such as years of birth or PIN codes.
def counting_sort_range(arr):
if not arr:
return arr
lo, hi = min(arr), max(arr)
count = [0] * (hi - lo + 1)
for x in arr:
count[x - lo] += 1
for i in range(1, len(count)):
count[i] += count[i - 1]
out = [0] * len(arr)
for x in reversed(arr):
count[x - lo] -= 1
out[count[x - lo]] = x
return out
print(counting_sort_range([3, -1, 0, -1, 2])) # [-1, -1, 0, 2, 3]
When Counting Sort Is the Wrong Tool
- Wide ranges: sorting five numbers between 1 and a billion would need an enormous count array. Use a comparison sort instead.
- Floating-point values or strings: they cannot be used directly as indices; map them to small integers first, or choose another algorithm.
- Memory-tight environments: it needs extra space for both the counts and the output.
Common bugs
- Walking the input forwards in the placement loop, which breaks stability.
- Forgetting to decrement before placing, which writes one position too far.
- Sizing the count array as
max_valinstead ofmax_val + 1.