八大排序算法的python实现(六)归并排序

时间:2022-12-23 08:00:03

代码:

#coding:utf-8
#author:徐卜灵
def merge(left,right):
    i,j = 0,0
    result = []
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result += left[i:]
    result += right[j:]
    return result


def Merge_sort(L):
    if len(L) <= 1:
        return L
    middle = len(L)/2
    left = Merge_sort(L[:middle])
    right = Merge_sort(L[middle:])
    return merge(left,right)

#参考网址http://python.jobbole.com/82270/
# def merge(left, right):
#     i, j = 0, 0
#     result = []
#     while i < len(left) and j < len(right):
#         if left[i] <= right[j]:
#             result.append(left[i])
#             i += 1
#         else:
#             result.append(right[j])
#             j += 1
#     result += left[i:]
#     result += right[j:]
#     return result
#
# def Merge_sort(lists):
#     # 归并排序
#     if len(lists) <= 1:
#         return lists
#     num = len(lists) / 2
#     left = Merge_sort(lists[:num])
#     right = Merge_sort(lists[num:])
#     return merge(left, right)
L = [49,38,65,97,76,13,67,47]
print Merge_sort(L)

二路归并,没有什么难以理解的,要注意递归的写法。还有返回值的问题。

时间复杂度:O(nlogn)

空间复杂读:O(nlogn)

跟堆排序、快速排序一样。

但它是稳定排序算法