1. 程式人生 > >演算法程式設計題-歸併排序

演算法程式設計題-歸併排序

def mergesort(li):
    if len(li)==1:
        return li
    mid = len(li)//2
    left = li[:mid]
    right = li[mid:]
    ll = mergesort(left)
    rl = mergesort(right)
    return merge(ll,rl)
def merge(left, right):
    result = []
    while len(left)>0 and len(right)>0:
        if left[0]>=right[0]:
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))
    result+=left
    result+=right
    return result
mergesort([5,4,3,2,1])