python实现
不递归的算法就是好懂
import datetime
import random
arr = [random.randint(0, 1000000) for x in range(500000)]
def radixSort(arr: list):
# 存放arr的桶
bucket = [[0] * len(arr) for x in range(10)]
# 存放各个位数字的个数
bucketCount = [0] * 10
# 取出最大的位数
maxLength = len(str(max(arr)))
# 根据最大位数来循环,最大3位数就循环3次
n = 1
for i in range(maxLength):
# 循环列表
for j in arr:
# 个、十、百、千、万位的数字
digit = j // n % 10
bucket[digit][bucketCount[digit]] = j
bucketCount[digit] += 1
index = 0
for k in range(10):
if bucketCount[k] != 0:
for l in range(bucketCount[k]):
arr[index] = bucket[k][l]
index += 1
bucketCount = [0] * 10
n *= 10
start = datetime.datetime.now().timestamp()
radixSort(arr)
end = datetime.datetime.now().timestamp()
print(f"总共花了{int(end - start)}s")