-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbucket_sort_github.py
More file actions
38 lines (27 loc) · 868 Bytes
/
bucket_sort_github.py
File metadata and controls
38 lines (27 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def bucket_sort(numbers):
"""
Bucket Sort for floating point numbers between 0 and 1
"""
bucket_count = len(numbers)
buckets = [[] for _ in range(bucket_count)]
# 1. Distribute numbers into buckets
for num in numbers:
index = int(num * bucket_count)
buckets[index].append(num)
# 2. Sort each bucket (using built-in sort)
for bucket in buckets:
bucket.sort()
# 3. Merge buckets
sorted_numbers = []
for bucket in buckets:
sorted_numbers.extend(bucket)
return sorted_numbers
def main():
data = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
print("--- Original array:")
print(data)
sorted_data = bucket_sort(data)
print("\n--- Sorted array:")
print(sorted_data)
if __name__ == "__main__":
main()