基数排序(Radix Sort)是一种非比较型整数排序算法,它根据数字的每个位数来进行排序。它的时间复杂度为O(d(n+k)),其中d是最大数字的位数,n是数字的个数,k是每个数字的取值范围。在某些情况下,基数排序比快速排序和归并排序更快。

下面是基数排序的Python代码实现,包括详细的注释和测试用例:

def radix_sort(arr):
    '''
    基数排序
    :param arr: 待排序数组
    :return: 排序后的数组
    '''
    # 找到最大数,确定要排序的轮数
    max_num = max(arr)
    rounds = len(str(max_num))

    # 每轮按照个位、十位、百位...的顺序排序
    for i in range(rounds):
        # 初始化桶
        buckets = [[] for _ in range(10)]
        # 分配:将每个数放到对应的桶中
        for num in arr:
            digit = (num // (10 ** i)) % 10
            buckets[digit].append(num)
        # 收集:将桶中的数按照顺序放回原数组中
        arr = [num for bucket in buckets for num in bucket]

    return arr

# 测试用例
print(radix_sort([3, 1, 5, 7, 2, 4, 9, 6, 8, 0]))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))  # [2, 24, 45, 66, 75, 90, 170, 802]
print(radix_sort([329, 457, 657, 839, 436, 720, 355]))  # [329, 355, 436, 457, 657, 720, 839]
Python 基数排序算法实现:代码详解及测试用例

原文地址: https://www.cveoy.top/t/topic/nFY9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录