Overview & Concept
Counting Sort is a non-comparison integer sorting algorithm that runs in linear O(n + k) time, where n is the number of elements and k is the range of key values. It works by counting the frequency of each distinct value, computing prefix sums to determine exact output positions, and placing elements directly into a sorted array.
How It Works
Frequency Counting: Tally occurrences of each integer in a count array of size k = max - min + 1.
Prefix Sum Accumulation: Transform count array so each index stores the cumulative total of smaller elements.
Right-to-Left Placement: Iterate through input backwards, placing elements at designated positions to guarantee stability.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n + k) | O(n + k) | O(n + k) | O(n + k) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure countingSort(A):
find min and max in A; range = max - min + 1
count = array of zeros of size range
for each x in A: count[x - min]++
compute prefix sums in count array
for i = n - 1 down to 0: // stable right-to-left
place A[i] into output[--count[A[i] - min]]
copy output array back to A
return A
end procedure- Frequency Invariant: The count array stores exact counts of every integer value in the input.
Advantages & Disadvantages
Key Advantages
- •Linear O(n + k) time: beats the theoretical O(n log n) comparison-based sorting limit.
- •Stable sorting algorithm.
Trade-offs & Limitations
- •Requires O(k) memory, which explodes if the range k is large relative to n.
- •Only applicable to integer or discrete enumerable keys.
Real-World Applications
Subroutine for Radix Sort
Digit-by-digit stable counting sort in Radix Sort.
Categorical Data Sorting
Sorting exam scores, ages, or status codes within bounded small ranges.
Decision Guide: When to Use
Ideal Scenarios
- ✓When sorting integer keys within a known, small range k (e.g. k ≤ O(n)).
Consider Alternatives When
- ✕When values have a vast range (e.g. 32-bit arbitrary hashes) or floating-point numbers.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.