计数排序(python)

计数排序

(思想:分类)图片来源:菜鸟教程
主要代码如下:

#计数排序
def countSort(markList):
    max = 0
    #获取列表最大值
    for value in markList:
        if value > max:
            max = value
    #定义新列表进行计数,长度为max+1(包括零)
    countList = [0 for i in range(max+1)]
    printList = []
    #开始计数
    for value in markList:
        countList[value] += 1
    #计数完毕,输出
    for i in range(len(countList)):
        while countList[i] > 0:
            printList.append(i)
            countList[i] -= 1
    return printList

可复制执行如下:

# 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 countSort(markList):
    max = 0
    for value in markList:
        if value > max:
            max = value
    countList = [0 for i in range(max+1)]
    printList = []
    for value in markList:
        countList[value] += 1
    for i in range(len(countList)):
        while countList[i] > 0:
            printList.append(i)
            countList[i] -= 1
    return printList

def main():
    global list
    generate()
    list = countSort(list)
    print("计数排序后数字列表如下:%s" % 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/104423647