DSA — Bucket Sort
What is Bucket Sort?
Distributes elements into buckets, sorts each bucket, then concatenates.
def bucket_sort(arr):
if not arr:
return arr
min_val = min(arr)
max_val = max(arr)
bucket_count = len(arr)
bucket_range = (max_val - min_val) / bucket_count
buckets = [[] for _ in range(bucket_count)]
for num in arr:
index = int((num - min_val) / bucket_range)
if index == bucket_count:
index -= 1
buckets[index].append(num)
result = []
for bucket in buckets:
result.extend(sorted(bucket))
return result
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(n + k) |
| Average | O(n + k) |
| Worst | O(n²) |
Where k is number of buckets.
Characteristics
- Stable sort (with stable inner sort)
- Works with floating point
- Performance depends on distribution
- Good for uniformly distributed data
Mini Practice
- Implement bucket sort
- Sort floating point numbers
- Choose optimal bucket count
- Compare with other sorts
Up Next
Continue with Depth First Search — DFS algorithm.
Related Topics
Frequently Asked Questions about Bucket Sort
What is Bucket Sort in DSA?
Bucket 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 Bucket 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 Bucket Sort.
Why is Bucket Sort important in DSA?
Bucket Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.