归并排序(python)

【归并排序思想】

分治的思想(递归)
图片来源:菜鸟教程

# coding = utf-8
import random
import sys
#归并排序
list = []
# 随机生成列表
def generate():
    n = int(input("请输入本次排序数字个数:"))
    while n > 0:
        list.append(random.randint(0,1000))
        n -= 1
    print("生成的数字列表如下:%s" %list)

def marge(leftList,rightList):
    otherList = []
    h = j = 0
    while j < len(leftList) and h < len(rightList):
        if leftList[j] < rightList[h]:
            otherList.append(leftList[j])
            j += 1
        else:
            otherList.append(rightList[h])
            h += 1
    if j == len(leftList):
        for i in rightList[h:]:
            otherList.append(i)
    else:
        for i in leftList[j:]:
            otherList.append(i)
    return otherList

# 对列表进行归并排序
def margeSort(markList):
    if len(markList) <= 1:
        return markList
    middle = len(markList) // 2
    leftList = margeSort(markList[:middle])
    rightList = margeSort(markList[middle:])
    return marge(leftList,rightList)

def main():
    generate()
    print("排序后数字列表如下:%s" % margeSort(list))

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.stderr.write("退出\n")
        sys.exit(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值