计数排序
(思想:分类)
主要代码如下:
#计数排序
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)