Skip to content

Commit 3b8cf4e

Browse files
author
Shriya Madan
committed
adding bucket sort in python
1 parent 695be28 commit 3b8cf4e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

bucket_sort.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Python3 program to sort an array using bucket sort
2+
def insertionSort(b):
3+
for i in range(1, len(b)):
4+
up = b[i]
5+
j = i - 1
6+
while j >= 0 and b[j] > up:
7+
b[j + 1] = b[j]
8+
j -= 1
9+
b[j + 1] = up
10+
return b
11+
12+
def bucketSort(x):
13+
arr = []
14+
slot_num = 10 # 10 means 10 slots, each slot's size is 0.1
15+
for i in range(slot_num):
16+
arr.append([])
17+
18+
# Put array elements in different buckets
19+
for j in x:
20+
index_b = int(slot_num * j)
21+
arr[index_b].append(j)
22+
23+
# Sort individual buckets
24+
for i in range(slot_num):
25+
arr[i] = insertionSort(arr[i])
26+
27+
# concatenate the result
28+
k = 0
29+
for i in range(slot_num):
30+
for j in range(len(arr[i])):
31+
x[k] = arr[i][j]
32+
k += 1
33+
return x
34+
35+
x = [0.897, 0.565, 0.656,
36+
0.1234, 0.665, 0.3434]
37+
38+
print(bucketSort(x))

0 commit comments

Comments
 (0)