Bucket Sort
def bucket_sort(arr):
# create buckets
n = len(arr)
buckets = [[] for _ in range(n)]
# distribute into buckets
for num in arr:
index = int(num * n)
buckets[index].append(num)
# sort by bucket, any sort algorithm can be used
for bucket in buckets:
bucket.sort()
# combine the buckets
sorted_arr = []
for bucket in buckets:
sorted_arr.extend(bucket)
return sorted_arr
import random
random.seed(42)
data = [round(random.random(), 2) for _ in range(10)]
print("Original Data:")
print(data)
sorted_data = bucket_sort(data)
print("Sorted Data:")
print(sorted_data)
# Original Data:
# [0.64, 0.03, 0.28, 0.22, 0.74, 0.68, 0.89, 0.09, 0.42, 0.03]
# Sorted Data:
# [0.03, 0.03, 0.09, 0.22, 0.28, 0.42, 0.64, 0.68, 0.74, 0.89]
Complexity
Type | Complexity |
---|---|
Time | O(n + k) |
Space | O(n) |
Stability
Stable