-
Notifications
You must be signed in to change notification settings - Fork 43
/
bucket_sort.py
48 lines (39 loc) · 1.41 KB
/
bucket_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#---------------------------------------------------------------
# BUCKET SORT
#---------------------------------------------------------------
# V0 : dev
# V1
# Time Complexity of Solution:
# Best Case O(n); Average Case O(n); Worst Case O(n)
from insertion_sort import insertion_sort
import math
DEFAULT_BUCKET_SIZE = 5
def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE):
if(len(myList) == 0):
print('You don\'t have any elements in array!')
minValue = myList[0]
maxValue = myList[0]
# For finding minimum and maximum values
for i in range(0, len(myList)):
if myList[i] < minValue:
minValue = myList[i]
elif myList[i] > maxValue:
maxValue = myList[i]
# Initialize buckets
bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
buckets = []
for i in range(0, bucketCount):
buckets.append([])
# For putting values in buckets
for i in range(0, len(myList)):
buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i])
# Sort buckets and place back into input array
sortedArray = []
for i in range(0, len(buckets)):
insertion_sort(buckets[i])
for j in range(0, len(buckets[i])):
sortedArray.append(buckets[i][j])
return sortedArray
# if __name__ == '__main__':
# sortedArray = bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95])
# print(sortedArray)