Skip to content

Commit bf72c27

Browse files
Merge pull request #252 from Kasa1905/feat/bucket-sort-py
Add Bucket Sort (Python)
2 parents c64882d + 59c7c5e commit bf72c27

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

ALGORITHMS/BucketSort.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def bucket_sort(array):
2+
# Create buckets
3+
n = len(array)
4+
buckets = [[] for _ in range(n)]
5+
6+
# Distributing the elements into buckets
7+
for value in array:
8+
bucket_index = int(n * value) # Assuming values are in the range [0, 1)
9+
if bucket_index >= n:
10+
bucket_index = n - 1 # Handle the case where value is 1.0
11+
buckets[bucket_index].append(value)
12+
13+
# Sort each bucket and concatenate the results
14+
index = 0
15+
for bucket in buckets:
16+
bucket.sort() # Sort individual buckets
17+
for value in bucket:
18+
array[index] = value # Concatenate the sorted buckets
19+
index += 1
20+
21+
# Main function to test the bucket sort
22+
if __name__ == "__main__":
23+
# Taking input from the user
24+
input_values = input("Enter floating-point numbers between 0 and 1, separated by spaces: ")
25+
26+
# Convert input string to a list of floats
27+
array = [float(x) for x in input_values.split()]
28+
29+
print("Original array:")
30+
print(array)
31+
32+
bucket_sort(array)
33+
34+
print("Sorted array:")
35+
print(array)

0 commit comments

Comments
 (0)