-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbucket-sort.py
46 lines (38 loc) · 1.38 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
# Python3 program to sort an array
# using bucket sort
def insertionSort(b):
for i in range(1, len(b)):
up = b[i]
j = i - 1
while j >= 0 and b[j] > up:
b[j + 1] = b[j]
j -= 1
b[j + 1] = up
return b
def bucketSort(input_list):
# Find maximum value in the list and use length of the list to determine which value in the list goes into which bucket
max_value = max(input_list)
size = max_value / len(input_list)
# Create n empty buckets where n is equal to the length of the input list
buckets_list = []
for x in range(len(input_list)):
buckets_list.append([])
# Put list elements into different buckets based on the size
for i in range(len(input_list)):
j = int(input_list[i] / size)
if j != len(input_list):
buckets_list[j].append(input_list[i])
else:
buckets_list[len(input_list) - 1].append(input_list[i])
# Sort elements within the buckets using Insertion Sort
for z in range(len(input_list)):
insertionSort(buckets_list[z])
# Concatenate buckets with sorted elements into a single list
final_output = []
for x in range(len(input_list)):
final_output = final_output + buckets_list[x]
return final_output
# Driver Code
x = [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]
print("Sorted Array is")
print(bucketSort(x))