How Counting Sort Works
Counting sort is a non-comparison sorting algorithm that counts the occurrences of each value and uses arithmetic to determine positions. It runs in linear time when the range of values (k) is not significantly larger than the number of elements (n).
Count the occurrences of each distinct value in the input. Compute a prefix sum of the counts to determine output positions. Place each element in its correct position using the prefix sum, decrementing the count after each placement.
Complexity
- Time
- O(n + k)
- Space
- O(k)
When to Use Counting Sort
- Integer data with a known, bounded range
- When O(n) time is required and extra space is acceptable
- As a sub-routine in radix sort