-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdated_merge_sort.py
More file actions
128 lines (90 loc) · 2.44 KB
/
updated_merge_sort.py
File metadata and controls
128 lines (90 loc) · 2.44 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import math
def main_algo(arr):
def find_levels(length):
val = length
count = 0
while val > 2:
val = math.ceil(val / 2)
count += 1
return count
def create_dic(lev):
store = {}
count = 1
while lev >= count:
store[count] = []
count += 1
return store
array = arr
level = find_levels(len(array))
store = create_dic(level)
count_store = {"count":0}
def update_dic(level,arr):
subject_list = store.get(level)
for i in arr:
subject_list.append(i)
store[level] = subject_list
def update_count(co):
sub = count_store.get("count")
sub += co
count_store["count"] = sub
def mergeSort(array, lev):
gain = 0
if len(array) > 1:
level = lev
r = len(array) // 2
L = array[:r]
M = array[r:]
mergeSort(L, level - 1)
mergeSort(M, level - 1)
if level != 0:
update_dic(level,L)
update_dic(level,M)
i = j = k = 0
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
gain += 1
update_count(gain)
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
def print_dic(dict):
for value in dict.values():
printList(value)
print(f"The length of array is {len(array)}")
printList(array)
mergeSort(array,level)
print("___________")
print_dic(store)
printList(array)
print(f"total comparisons were {count_store.get('count')}")
print("___________")
print("___________")
main_algo([5, 3, 1, 2, 8, 4, 7, 6])
str_list = []
for i in range(1,51):
str_list.append(i)
main_algo(str_list)
rev = []
for i in range(50,0,-1):
rev.append(i)
main_algo(rev)
from random import randint
random = []
for i in range(1,51):
random.append(randint(1,100))
main_algo(random)