|
发表于 2023-10-19 20:00:49
|
显示全部楼层
基数排序是一种非比较的排序算法,适用于对整数进行排序。它的基本思想是将待排序的数字按照个位、十位、百位等位数进行排序,每一位都使用稳定的排序算法,如计数排序或桶排序。
基数排序的步骤如下:
1. 找到待排序数字中最大的数,确定需要进行多少次排序。
2. 从个位开始,对待排序数字按照当前位数进行计数排序或桶排序。
3. 按照上一步的排序结果,继续对下一位进行排序,直到最高位。
以下是一个基数排序的示例代码:
- def counting_sort(arr, exp):
- n = len(arr)
- output = [0] * n
- count = [0] * 10
- for i in range(n):
- index = arr[ i] // exp
- count[index % 10] += 1
- for i in range(1, 10):
- count[ i] += count[i - 1]
- i = n - 1
- while i >= 0:
- index = arr[ i] // exp
- output[count[index % 10] - 1] = arr[ i]
- count[index % 10] -= 1
- i -= 1
- for i in range(n):
- arr[ i] = output[ i]
- def radix_sort(arr):
- max_num = max(arr)
- exp = 1
- while max_num // exp > 0:
- counting_sort(arr, exp)
- exp *= 10
- return arr
复制代码
在这个示例代码中, counting_sort 函数用于对数组按照当前位数进行计数排序, radix_sort 函数则是基数排序的主函数。通过不断地对每一位进行排序,最终可以得到一个有序的数组。
希望对你有所帮助!如果有任何疑问,请随时提问。 |
|