-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.py
85 lines (63 loc) · 1.57 KB
/
MergeSort.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
78
79
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) //2
left = alist[:mid]
right = alist[mid:]
mergeSort(left)
mergeSort(right)
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
alist[k] = left[i]
i += 1
k += 1
else:
alist[k] = right[j]
j += 1
k += 1
while i < len(left):
alist[k] = left[i]
i += 1
k += 1
while j < len(right):
alist[k] = right[j]
j += 1
k += 1
templist = [5,2,6,7,8,6,4]
mergeSort(templist)
print(templist)
def mergeSort2(alist):
if len(alist) <= 1:
return alist
else:
i = 0
j = 0
k = 0
mid = len(alist) // 2
left = alist[:mid]
right = alist[mid:]
left = mergeSort2(left)
right = mergeSort2(right)
while i < len(left) and j < len(right):
if left[i] < right[j]:
alist[k] = left[i]
k = k + 1
i = i + 1
else:
alist[k] = right[j]
k = k + 1
j = j + 1
while i < len(left):
alist[k] = left[i]
k = k + 1
i = i + 1
while j < len(right):
alist[k] = right[j]
k = k + 1
j = j + 1
return alist
templist = [5,2,6,7,8,6,4]
mergeSort2(templist)
print(templist)