算法导论:归并排序算法之python实现

A = [99, 38, 65, 97, 76, 13, 27, 49]
# 排序步骤
# A = [99, 38, 65, 97][76, 13, 27, 49]
# A = [99, 38][65, 97][76, 13][27, 49]
# A = [38, 99][65, 97][13, 76][27, 49]
# A = [38, 65, 97, 99][13, 27, 49, 76]
# A = [13, 27, 38, 49, 65, 76, 97, 99]


def merge(A, p, q, r):
    n1 = q - p + 1
    n2 = r - q
    L = []
    R = []
    for i in range(n1):
        L.append(A[p + i])
    for j in range(n2):
        R.append(A[q + 1 + j])

    L.append(float("inf"))
    R.append(float("inf"))
    i = 0
    j = 0
    for k in range(p, r + 1):
        if L[i] <= R[j]:
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1


import math


def merge_sort(A, p, r):
    if p < r:
        q = math.floor((p + r) / 2)
        merge_sort(A, p, q)
        merge_sort(A, q + 1, r)
        merge(A, p, q, r)


merge_sort(A, 0, 7)
print(A)

你可能感兴趣的:(算法导论)