DSA — Counting Sort
What is Counting Sort?
Counts occurrences of each element and uses them to reconstruct the sorted array.
def counting_sort(arr):
if not arr:
return arr
max_val = max(arr)
min_val = min(arr)
range_val = max_val - min_val + 1
count = [0] * range_val
output = [0] * len(arr)
# Count occurrences
for num in arr:
count[num - min_val] += 1
# Cumulative count
for i in range(1, len(count)):
count[i] += count[i - 1]
# Build output
for num in reversed(arr):
output[count[num - min_val] - 1] = num
count[num - min_val] -= 1
return output
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(n + k) |
| Average | O(n + k) |
| Worst | O(n + k) |
Where k is the range of input.
Characteristics
- Stable sort
- Not comparison-based
- Works with integers
- Limited by range of values
Mini Practice
- Implement counting sort
- Sort with negative numbers
- Use for string sorting
- Compare with comparison sorts
Up Next
Continue with Radix Sort — digit-by-digit sorting.
Related Topics
Frequently Asked Questions about Counting Sort
What is Counting Sort in DSA?
Counting Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Counting Sort?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Counting Sort.
Why is Counting Sort important in DSA?
Counting Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.