O(n) O(kn)
NB O(nlogn)
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
def radix_sort(li):
max_num = max(li) # 最大值 9->1, 99->2, 888->3, 10000->5
# 迭代多少次 it=0是个位 it=1是十位 it=2是百位
it = 0
# 10的it倍数 10的零次方是1 1小于9 10的一次方是2次 10的2次方是100是3次 10的3次方是1000
# 位数是几我们就做几次循环
while 10 ** it <= max_num:
# 分桶
buckets = [[] for _ in range(10)]
# 把这个元素放到几号桶
for var in li:
# 987 it=1 987//10=98 98%10=8; --取第二位 it=2 987//100=9 9%10=9 --取第三位 %10就是去于
digit = (var // 10 ** it) % 10
# 找到它对应的桶 分桶完成
buckets[digit].append(var)
li.clear()
for buc in buckets:
# 把数重新写回li
li.extend(buc)
# 到这又重新建桶,分桶
it += 1
import random#
li = [random.randint(0, 100) for _ in range(100)]
random.shuffle(li)
print(li)
radix_sort(li)
print(li)
E:\py3\venv\Scripts\python.exe E:/py3/基数排序.py
[37, 66, 40, 37, 53, 61, 53, 60, 73, 25, 29, 13, 71, 39, 92, 12, 82, 72, 89, 22, 91, 60, 55, 15, 25, 32, 72, 35, 2, 81, 99, 93, 61, 11, 43, 32, 46, 22, 72, 14, 75, 60, 45, 95, 23, 50, 13, 7, 62, 81, 63, 11, 27, 4, 62, 20, 44, 12, 3, 97, 77, 78, 64, 22, 22, 84, 25, 12, 9, 95, 6, 91, 40, 57, 72, 0, 62, 90, 57, 8, 75, 46, 14, 69, 80, 59, 91, 90, 33, 95, 56, 80, 74, 92, 43, 34, 38, 47, 69, 40]
[0, 2, 3, 4, 6, 7, 8, 9, 11, 11, 12, 12, 12, 13, 13, 14, 14, 15, 20, 22, 22, 22, 22, 23, 25, 25, 25, 27, 29, 32, 32, 33, 34, 35, 37, 37, 38, 39, 40, 40, 40, 43, 43, 44, 45, 46, 46, 47, 50, 53, 53, 55, 56, 57, 57, 59, 60, 60, 60, 61, 61, 62, 62, 62, 63, 64, 66, 69, 69, 71, 72, 72, 72, 72, 73, 74, 75, 75, 77, 78, 80, 80, 81, 81, 82, 84, 89, 90, 90, 91, 91, 91, 92, 92, 93, 95, 95, 95, 97, 99]
Process finished with exit code 0