Counting Sort 🔢
Back to algorithms list.Functionality
Counting Sort is a non-comparison-based sorting algorithm that works efficiently when sorting integers within a known, limited range. Instead of comparing elements, it counts how many times each distinct value occurs and then uses this information to place each value in the correct position. The algorithm works in three main steps:
- Count the occurrences of each value and store them in a count array.
- Transform the count array to show the positions of each value in the output array.
- Use the count array to place elements in the correct position in the output array.
This method is stable and runs in linear time when the range of input values (k) is not significantly larger than the number of elements (n).
Advantages
- Fast for small ranges: When the range of input values is not too large, Counting Sort is very efficient with a time complexity of O(n + k).
- Stability: Maintains the relative order of equal elements, which is useful for sorting data with secondary keys.
- Non-comparative: Ideal for scenarios where traditional comparison-based sorting isn't optimal.
Disadvantages
- Limited to integers or small ranges: It is not suitable for sorting large ranges of values or floating-point numbers directly.
- Extra space needed: Requires additional memory for the count array and the output array, making it less space-efficient.
- Not in-place: Counting Sort does not sort the array in-place, which can be a drawback in memory-constrained environments.
Conclusion
Counting Sort is especially useful for sorting integers in scenarios like sorting grades, age groups, or any data where the possible values are limited and known in advance.
Source: Article about Counting sort on wikipedia.org
Source code: github.com/danielnagel/algorithms