-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.py
74 lines (44 loc) · 976 Bytes
/
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
def main():
A=[3,5,6,7,2,4,8,9]
low=0
high=7
print('\n\nArray before sorting:\n',' ',A)
mergesort(A,low,high)
print('\n\nArray after sorting:\n',' ',A,'\n')
def mergesort(A,low,high):
if low<high:
mid=int(low+(high-low)/2)
mergesort(A,low,mid)
mergesort(A,mid+1,high)
merge(A,low,mid,high)
return
def merge(A,low,mid,high):
n1=mid-low+1
n2=high-mid
L=[]
R=[]
for i in range(0,n1):
L.append(A[low+i])
for i in range(0,n2):
R.append(A[mid+1+i])
l=0
r=0
i=low
while(l<n1 and r<n2):
if L[l]> R[r]:
A[i]=R[r]
r=r+1
else:
A[i]=L[l]
l=l+1
i=i+1
while l<n1:
A[i]=L[l]
l=l+1
i=i+1
while r<n2:
A[i]=R[r]
r=r+1
i=i+1
if __name__ == '__main__':
main()