python实现计数排序

计数排序有局限性,最小值和最大值决定着数组的长度,如果分配均匀的话可以用
# @File: count_sort

import random


def count_sort(li, max_num=100):
    count = [0 for i in range(max_num + 1)]
    for val in li:
        count[val] += 1
    li.clear()
    for i in range(len(count)):
        # i这个数出现了count[i]次
        # li.extend([i]*count[i])
        for _ in range(count[i]):
            li.append(i)


li = [random.randint(0, 100) for _ in range(20)]
count_sort(li)
print(li)

 

posted @ 2018-12-24 09:48  小学弟-  阅读(266)  评论(0编辑  收藏  举报