分治算法-归并排序-递归法实现

# 1. 切分,
# 2. 排序
# 3. 合并


def top_down(arr):
    if len(arr) == 1:
        return arr
    arr1, arr2 = split_(arr)
    res1 = top_down(arr1)
    res2 = top_down(arr2)
    res = sort_(res1,res2)
    return res


def split_(arr):# 切分
    """
    :return: arr_1,arr_2(切分后的结果)
    """
    arr_1 = arr[0:len(arr)//2]
    arr_2 = arr[len(arr)//2:]
    return arr_1,arr_2


def sort_(a,b):# 排序
    res = []
    a_index = 0
    b_index = 0
    while a_index != len(a) and b_index != len(b):
        if a[a_index]>b[b_index]:
            res.append(b[b_index])
            b_index += 1
        else:
            res.append(a[a_index])
            a_index += 1
    if a_index!=len(a):
        res.extend(a[a_index:])
    else:
        res.extend(b[b_index:])
    return res


if __name__ == '__main__':
    arr = [6,3,-2,0,-1,5,9,10,9]
    res = top_down(arr)
    print(res)

<<<
[-2, -1, 0, 3, 5, 6, 9, 9, 10]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值