Merge Sort(归并排序)
伪代码
MERGE(A, p, q, r)
n1 = q-p+1
n2 = r-q
creat L[1..n1+1], R[1..n2+1]
for i = 1 to n1
do L[i] = A[p+i-1]
for j = 1 to n2
do R[j] = A[q+j]
L[n1+1] = +inf
R[n2+1] = +inf
i, j = 1, 1
for k = p to r
do if L[i]<=R[j]
then A[k] = L[i]
i = i+1
else A[k] = R[j]
j = j+1
MERGE-SORT(A, p, r)
if p<r
then q = int((p+r)/2)
MERGE-SORT(A, p, q)
MERGE-SORT(A, q+1, r)
MERGE(A, p, q, r)
python实现
from datamodel import sequence
def merge(A, p, q, r):
n1 = q-p+1
n2 = r-q
L = [None] + list(range(1, n1+2))
R = [None] + list(range(1, n2+2))
for i in range(1, n1+1):
L[i] = A[p+i-1]
for j in range(1, n2+1):
R[j] = A[q+j]
L[n1+1] = float('inf')
R[n2+1] = float('inf')
i, j = 1, 1
for k in range(p, r+1):
if L[i]<=R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
def mergeSort(A, p, r):
if p<r:
q = (p+r) // 2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)
def MERGESORT(s):
assert(isinstance(s, sequence))
A = s.data
p, r = 1, s.length
mergeSort(A, p, r)
assert(s.isSorted())
print("succeed")
if __name__ == '__main__':
s1 = sequence([5,2,4,6,1,3])
MERGESORT(s1)
s1.printData()
运行结果
succeed
[1, 2, 3, 4, 5, 6]
参考
《算法导论》