手写归并排序 python3

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Victordas/article/details/82931193

在这里插入图片描述

本地测试:

def mergesort(a,b):
    c = []
    len1 = len(a)
    len2 = len(b)
    j,i = 0, 0
    while i < len1 and j < len2:
        if a[i] > b[j]:
            c.append(b[j])
            j += 1
        else:
            c.append(a[i])
            i += 1
    while i < len1:
        c.append(a[i])
        i += 1
    while j < len2:
        c.append(b[j])
        j += 1
    return c

def separateList(q, first, last):
    if first < last:
        mid = int((first + last)/2)
        separateList(q, first, mid)
        separateList(q, mid+1, last)
        a = q[first:mid+1]
        b = q[mid+1:last+1]
        c = mergesort(a,b)
        start = first
        for i in c:
            q[start] = i
            start += 1
        return q

if __name__ == "__main__":
    q = [2, 3, 1, 7, 5, 9, 10, 4, 6, 8]
    first = 0
    last = len(q) - 1
    print(separateList(q, first, last))

参考博客:https://blog.csdn.net/AQ_cainiao_AQ/article/details/75571000

猜你喜欢

转载自blog.csdn.net/Victordas/article/details/82931193