Skip to content

Commit 0febf9c

Browse files
authored
Merge pull request #27 from shriyaMadan/master
Bucket-Sort.py
2 parents 95db079 + a489ced commit 0febf9c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Diff for: Bucket Sort.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Bucket sort is a comparison sort algorithm that operates on elements by dividing them into different buckets and then sorting these buckets individually. Each bucket is sorted individually using a separate sorting algorithm or by applying the bucket sort algorithm recursively. Bucket sort is mainly useful when the input is uniformly distributed over a range.
2+
3+
Assume one has the following problem in front of them:
4+
5+
One has been given a large array of floating point integers lying uniformly between the lower and upper bound. This array now needs to be sorted. A simple way to solve this problem would be to use another sorting algorithm such as Merge sort, Heap Sort or Quick Sort. However, these algorithms guarantee a best case time complexity of O(n log(n)). However, using bucket sort, the above task can be completed in O(n) time. Let's have a closer look at it.
6+
7+
Consider one needs to create an array of lists, i.e of buckets. Elements now need to be inserted into these buckets on the basis of their properties. Each of these buckets can then be sorted individually using Insertion Sort.
8+
9+
Time Complexity:
10+
If one assumes that insertion in a bucket takes O(1) time, then steps 1 and 2 of the above algorithm clearly take O(n) time.

Diff for: 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)