1. 程式人生 > >python的歸併排序(mergesort)實現

python的歸併排序(mergesort)實現

程式碼:

def merge(left, right):
    res = []
    while left and right:
        if left[0] < right[0]:
            res.append(left.pop(0))
        else:
            res.append(right.pop(0))
    res = res + left + right
    return res

def mergesort(lists):
    if len(lists) <= 1:
        return lists
    mid =
len(lists)//2 left = mergesort(lists[:mid]) right = mergesort(lists[mid:]) return merge(left,right)

測試:

for time in range(10):
    a = [random.randint(0,1000) for _ in range(100)] # 生成長度為100的整型陣列,元素大小為(0,1000]
    res = mergesort(a)
    print(bool(res == sorted(a)))