归并排序(python实现)

"""
归并排序
典型的分而治之
递归实现分治的效果
"""


def merge_sort(alist):
    if len(alist) <= 1:
        return alist
    # 分治排序
    mid = len(alist)//2
    left = merge_sort(alist[:mid])
    right = merge_sort(alist[mid:])
    # 合并
    return merge(left, right)

def merge(left, right):
    """合并操作,将两个有序数组left[]和right[]合并成一个大的有序数组"""
    # left 与 right 的下标指针
    l, r = 0, 0
    result = []
    while l < len(left) and r < len(right):
        if left[l] < right[r]:
            result.append(left[l])
            l += 1
        else:
            result.append(right[r])
            r += 1
    result += left[l:]
    result += right[r:]
    return result
posted @ 2019-12-13 00:58  L1m1t  阅读(177)  评论(0编辑  收藏  举报