归并排序(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)
发布了59 篇原创文章 · 获赞 2 · 访问量 1946

猜你喜欢

转载自blog.csdn.net/weixin_43148062/article/details/104397895