归并排序

先分再治

def merge_sort(data):
    if len(data)==1:
        return data
    mid = len(data) // 2
    print(mid)
    left, right = data[:mid], data[mid:]
    return merge(merge_sort(left), merge_sort(right))
def merge(l1, l2):
    result = []
    while len(l1)>0 and len(l2)>0:
        if l1[0] >= l2[0]:
            result.append(l2.pop(0))
        else:
            result.append(l1.pop(0))
    result += l1
    result += l2
    return result
d = [33,2,11,8,7,12]
merge_sort(d)
    

 

posted @ 2022-07-18 22:42  今夜无风  阅读(17)  评论(0编辑  收藏  举报