-
Notifications
You must be signed in to change notification settings - Fork 1
/
bucket.py
77 lines (73 loc) · 2.17 KB
/
bucket.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def bucket_sort_float(array):
bucket=[]
for i in range(len(array)):
bucket.append([])
for i in array:
key=int(10*i)
bucket[key].append(i)
for i in bucket:
i.sort()
nl=[]
for i in bucket:
nl.extend(i)
return nl
def bucket_sort_int(array):
max_element_len=len(str(max(array)))
bucket=[]
nl=[]
for i in range(10):
bucket.append([])
for i in array:
index=len(str(i))
bucket[index].append(i)
for i in bucket:
i.sort()
nl.extend(i)
return nl
if __name__ == '__main__':
array=[0.11,0.22,0.55,0.33,0.21,0.65,0.69]
# array = [6, 5, 1, 123, 24, 324, 3, 5, 45, 346, 5, 626, 6, 26]
if type(array[0])==type(12):
new_array=bucket_sort_int(array)
print(f"ARRAY BEFORE SORTING : {array}\nARRAY AFTER SORTING : {new_array}")
elif type(array[0])==type(0.1221):
new_array = bucket_sort_float(array)
print(f"ARRAY BEFORE SORTING : {array}\nARRAY AFTER SORTING : {new_array}")
# ------------------------------------------------OR---------------------------------------------------------------------------------------------
# def insertion_sort(array):
# for i in range(1, len(array)):
# temp = array[i]
# j = i - 1
# while j >= 0 and temp < array[j]:
# array[j + 1] = array[j]
# j -= 1
# array[j + 1] = temp
# return array
#
#
# def bucket_sort(array):
# bucket = []
# for i in range(len(array)):
# bucket.append([])
# for i in array:
# key = int(10 * i)
# bucket[key].append(i)
# new_list = []
# # print(bucket)
# for i in range(len(bucket)):
# sort_in = insertion_sort(bucket[i])
# new_list.append(sort_in)
# i += 1
# print(new_list)
#
# nl = []
# for i in new_list:
# nl.extend(i)
#
# return nl
#
#
# if __name__ == '__main__':
# array = [0.11, 0.22, 0.55, 0.33, 0.21, 0.65, 0.69]
# new_array = bucket_sort(array)
# print(f"ARRAY BEFORE SORTING : {array}\nARRAY AFTER SORTING : {new_array}")