对列表进行排序,已知列表中的数范围都在0到100之间,设计时间复杂度为O(n)的算法
例如 1 3 2 4 1 2 3 1 3 5
值是当前有几个数
0 0
1 0
2 0
3 0
4 0
5 0
#每个值计数加1 得到最后是
1 1 1 2 2 3 3 3 4 5
for _ in range(n)中
- _ 是占位符, 表示不在意变量的值 只是用于循环遍历n次。
- _是一个循环标志,也可以用i,j 等其他字母代替,下面的循环中不会用到,起到的是循环此数的作用
# _*_coding:utf-8_*_
#传一个最大是100的
def count_sort(li, max_count=100):
count = [0 for _ in range(max_count+1)]
for val in li:
#下标val
count[val] += 1
#li清空
li.clear()
#要需要下标和值
for ind, val in enumerate(count):
for i in range(val):
li.append(ind)
def sys_sort(li):
li.sort()
import random, copy
#20个数我生成100个
li = [random.randint(0,20) for _ in range(100)]
print(li)
count_sort(li)
print(li)
E:\py3\venv\Scripts\python.exe E:/py3/jishu.py
[15, 7, 9, 18, 18, 5, 3, 1, 14, 2, 6, 7, 18, 3, 4, 16, 12, 9, 20, 17, 16, 5, 5, 1, 9, 17, 18, 11, 16, 3, 8, 19, 9, 4, 2, 16, 1, 19, 6, 7, 4, 12, 5, 16, 3, 12, 13, 16, 6, 9, 7, 20, 5, 19, 19, 15, 18, 11, 3, 17, 14, 6, 3, 19, 2, 9, 14, 9, 0, 4, 10, 19, 10, 5, 4, 9, 20, 6, 0, 11, 5, 2, 10, 5, 1, 20, 3, 12, 5, 0, 0, 18, 18, 7, 6, 2, 8, 7, 3, 16]
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 13, 14, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20]
Process finished with exit code 0