伪代码
Coddy 基数排序:数据结构与算法系列 课程的第 4 课,共 9 课。
countingSortByDigit(array, exp):
n = length(array)
output = array of size n
count = array of 10 zeros
for each x in array: # tally each digit
count[(x / exp) % 10] += 1
for d from 1 to 9: # running totals -> positions
count[d] += count[d - 1]
for k from n-1 down to 0: # place from the back (stable)
d = (array[k] / exp) % 10
count[d] -= 1
output[count[d]] = array[k]
return output
radixSort(array):
max = largest value in array
exp = 1
while max / exp > 0:
array = countingSortByDigit(array, exp)
exp = exp * 10- exp 表示位值:个位是 1,十位是 10,百位是 100。
(x / exp) % 10可以提取出该位上的数字。 - countingSortByDigit 是对单个数位进行的稳定排序:它会统计每个数字出现的次数,将这些计数转换为位置,然后从后往前放置元素,以保留顺序。
- radixSort 只需对每个数位各执行一次这趟排序,当
exp大于最大数时停止。
亲手试试
这节课没有代码挑战。
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基数排序:数据结构与算法系列中的所有课
自己练习: C 在线编译器