MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / radix_sort

Function radix_sort

publication/code/chapter07/radix_sort.rs:3–43  ·  view source on GitHub ↗
(nums: &mut [usize])

Source from the content-addressed store, hash-verified

1// radix_sort.rs
2
3fn radix_sort(nums: &mut [usize]) {
4 if nums.len() < 2 { return; }
5
6 // 找到最大的数,它的位最多
7 let max_num = match nums.iter().max() {
8 Some(&x) => x,
9 None => return,
10 };
11
12 // 找最接近且 >= nums 长度的 2 的次幂值作为桶大小,如:
13 // 最接近且 >= 10 的 2 的次幂值是 2^4 = 16
14 // 最接近且 >= 17 的 2 的次幂值是 2^5 = 32
15 let radix = nums.len().next_power_of_two();
16
17 // digit 代表小于某个位对应桶的所有数
18 // 个、十、百、千分别在 1、2、3、4 位
19 // 起始从个位开始,所以是 1
20 let mut digit = 1;
21 while digit <= max_num {
22 // 闭包函数:计算数据在桶中的位置
23 let index_of = |x| x / digit % radix;
24
25 // 计数器
26 let mut counter = vec![0; radix];
27 for &x in nums.iter() {
28 counter[index_of(x)] += 1;
29 }
30 for i in 1..radix {
31 counter[i] += counter[i-1];
32 }
33
34 // 排序
35 for &x in nums.to_owned().iter().rev() {
36 counter[index_of(x)] -= 1;
37 nums[counter[index_of(x)]] = x;
38 }
39
40 // 跨越桶
41 digit *= radix;
42 }
43}
44
45fn main() {
46 let mut nums = [54,32,99,18,75,31,43,56,21,22];

Callers 1

mainFunction · 0.70

Calls 3

lenMethod · 0.45
maxMethod · 0.45
iterMethod · 0.45

Tested by

no test coverage detected