Skip to content

Commit 3128198

Browse files
committed
added bucket sort program
1 parent 1c73e2d commit 3128198

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ In case, the list becomes too big in the future you can use `cmd + f` or `ctrl +
3333
- [Linear Search](./searching/linearsearch.py)
3434
- [Sorting](./sorting)
3535
- [Bubble Sort](./sorting/bubblesort.py)
36+
- [Bucket Sort](./sorting/bucketsort.py)
3637
- [Insertion Sort](./sorting/insertionsort.py)
3738
- [Merge Sort](./sorting/mergesort.py)
3839
- [Quick Sort](./sorting/quicksort.py)

sorting/bucketsort.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def bucket_sort(arr):
2+
# Find the maximum and minimum values in the array
3+
max_val = max(arr)
4+
min_val = min(arr)
5+
n = len(arr)
6+
7+
# Calculate the range and the size of each bucket
8+
bucket_range = (max_val - min_val) / (n - 1)
9+
10+
# Create empty buckets
11+
buckets = [[] for _ in range(n)]
12+
13+
# Put elements into their respective buckets
14+
for num in arr:
15+
index = int((num - min_val) // bucket_range)
16+
buckets[index].append(num)
17+
18+
# Sort elements within each bucket using insertion sort
19+
for i in range(n):
20+
insertion_sort(buckets[i])
21+
22+
# Concatenate sorted elements from each bucket
23+
k = 0
24+
for i in range(n):
25+
for num in buckets[i]:
26+
arr[k] = num
27+
k += 1
28+
29+
def insertion_sort(bucket):
30+
for i in range(1, len(bucket)):
31+
key = bucket[i]
32+
j = i - 1
33+
while j >= 0 and bucket[j] > key:
34+
bucket[j + 1] = bucket[j]
35+
j -= 1
36+
bucket[j + 1] = key
37+
38+
# Example usage
39+
arr = [0.42, 0.32, 0.91, 0.01, 0.72, 0.63, 0.35]
40+
print("Unsorted array:", arr)
41+
bucket_sort(arr)
42+
print("Sorted array:", arr)

0 commit comments

Comments
 (0)