基于python的归并排序

之前看过C的归并排序,理解的不是很好,不能应用于题目上(本人太菜了)

相比较于C,python的归并排序代码超短的,也比较好理解

import math
def merge_sort(sequence):
    if(len(sequence)<2):
        return sequence
    mid=math.floor(len(sequence)/2)
    left,right=sequence[0:mid],sequence[mid:]
    return merge(merge_sort(left),merge_sort(right))
def merge(left,right):
    result=[]
    while left and right:
        if left[0] <=right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    while left:
        result.append(left.pop(0))
    while right:
        result.append(right.pop(0))
    return result
a=[124,53,2,5,342,6,78,5,8,9,1,2,67,758758,5353552,54242]
print(merge_sort(a))
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注