Skip to content

Commit e8a36b1

Browse files
committed
Added Bucket Sort implementation
1 parent 0f2edef commit e8a36b1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

sorts/bucket_sort.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Author: OMKAR PATHAK
2+
# This program will illustrate how to implement bucket sort algorithm
3+
4+
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
5+
# elements of an array into a number of buckets. Each bucket is then sorted individually, either using
6+
# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
7+
# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
8+
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
9+
# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
10+
# involve the number of buckets.
11+
12+
# Time Complexity of Solution:
13+
# Best Case O(n); Average Case O(n); Worst Case O(n)
14+
15+
from P26_InsertionSort import insertionSort
16+
import math
17+
18+
DEFAULT_BUCKET_SIZE = 5
19+
20+
def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE):
21+
if(len(myList) == 0):
22+
print('You don\'t have any elements in array!')
23+
24+
minValue = myList[0]
25+
maxValue = myList[0]
26+
27+
# For finding minimum and maximum values
28+
for i in range(0, len(myList)):
29+
if myList[i] < minValue:
30+
minValue = myList[i]
31+
elif myList[i] > maxValue:
32+
maxValue = myList[i]
33+
34+
# Initialize buckets
35+
bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
36+
buckets = []
37+
for i in range(0, bucketCount):
38+
buckets.append([])
39+
40+
# For putting values in buckets
41+
for i in range(0, len(myList)):
42+
buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i])
43+
44+
# Sort buckets and place back into input array
45+
sortedArray = []
46+
for i in range(0, len(buckets)):
47+
insertionSort(buckets[i])
48+
for j in range(0, len(buckets[i])):
49+
sortedArray.append(buckets[i][j])
50+
51+
return sortedArray
52+
53+
if __name__ == '__main__':
54+
sortedArray = bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95])
55+
print(sortedArray)

0 commit comments

Comments
 (0)