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

Function counting_sort

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

Source from the content-addressed store, hash-verified

1// counting_sort.rs
2
3fn counting_sort(nums: &mut [usize]) {
4 if nums.len() < 2 { return; }
5
6 // 桶数量为 nums 中最大值加 1,保证数据都有桶放
7 let max_bkt_num = 1 + nums.iter().max().unwrap();
8 let mut counter = vec![0; max_bkt_num];
9
10 // 将数据标记到桶
11 for &v in nums.iter() {
12 counter[v] += 1;
13 }
14
15 // 数据写回原 nums 切片
16 // j 表示 nums 的下标
17 let mut j = 0;
18 for i in 0..max_bkt_num {
19 while counter[i] > 0 {
20 nums[j] = i;
21 counter[i] -= 1;
22 j += 1;
23 }
24 }
25}
26
27fn main() {
28 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