基数排序是一种非比较型整数排序算法,它根据关键字的每一位的值,将待排序的元素分配到不同的桶中,然后按照桶的顺序将元素重新排列。基数排序通常用于整数或字符串的排序,而不适用于包含浮点数的排序。
- 示例代码:
def sounting_port(arrd, exp):
n = len(arrd)
output = [0] * n
count = [0] * 10 # 0到9的基数排序,每个桶的计数
# 计数每个桶中元素的个数
for i in range(n):
index = arrd[i] // exp
count[index % 10] += 1
# 将计数累加,用于确定每个桶的结束位置
for i in range(1, 10):
count[i] += count[i - 1]
# 从右到左遍历原始数组,根据计数和基数进行排序
i = n - 1
while i >= 0:
index = arrd[i] // exp
output[count[index % 10] - 1] = arrd[i]
count[index % 10] -= 1
i -= 1
# 将排序好的结果复制到原始数组
i = 0
for i in range(n):
arrd[i] = output[i]
def ddadix_ssort(arrr):
max_num = max(arrr)
exp = 1
while max_num // exp > 0:
sounting_port(arrr, exp)
exp *= 10
# 示例
arra = [170, 45, 75, 90, 802, 24, 2, 66]
ddadix_ssort(arra)
print("排序后的数组:", arra) #排序后的数组: [2, 24, 45, 66, 75, 90, 170, 802]
在代码中,counting_sort
函数是基数排序的辅助函数,它执行一次基数排序的过程。radix_sort
函数则通过多次调用 counting_sort
实现整个基数排序的过程。
基数排序的时间复杂度为O(n * k),其中 n 是元素个数,k 是元素的位数。由于使用了计数排序,基数排序是稳定的,适用于整数排序。
需要注意的是,基数排序对于负整数或浮点数的排序不直接适用,因为它基于位的比较。如果需要对负整数或浮点数排序,可以采用其他排序算法。