-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.py
More file actions
41 lines (34 loc) · 728 Bytes
/
MergeSort.py
File metadata and controls
41 lines (34 loc) · 728 Bytes
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
# Merge sort.chapter2.3.1
__author__ = 'ShiYujin'
__date__ = '2015.5.24'
def merge(A, p, q, r):
import copy
L = copy.deepcopy(A[p:q])
R = copy.deepcopy(A[q:r])
L.append(float("inf")) # sentinel
R.append(float("inf"))
i = 0
j = 0
for k in range(p, r):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
return A
def MSort(A, p, r):
if p < r - 1:
q = (p + r) / 2
MSort(A, p, q)
MSort(A, q, r)
merge(A, p, q, r)
return A
def MergeSort(A):
a = A[:]
return MSort(a, 0, a.__len__())
# little test
a = [6, 5, 4, 3, 2, 1, 0]
a = MergeSort(a)
for i in a:
print(i)