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

Function counting_sort

code/chapter06/counting_sort.rs:3–22  ·  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() <= 1 { return; }
5
6 // 桶数量为 nums 中最大值加 1,保证数据都有桶放
7 let max_bkt_num = nums.iter().max().unwrap() + 1;
8 let mut counter = vec![0; max_bkt_num];
9 for &v in nums.iter() {
10 counter[v] += 1; // 将数据标记到桶
11 }
12
13 // 数据写回原 nums 切片
14 let mut j = 0;
15 for i in 0..max_bkt_num {
16 while counter[i] > 0 {
17 nums[j] = i;
18 counter[i] -= 1;
19 j += 1;
20 }
21 }
22}
23
24fn main() {
25 let mut nums = [54,32,99,18,75,31,43,56,21,22,1,100];

Callers 1

mainFunction · 0.70

Calls 3

lenMethod · 0.45
maxMethod · 0.45
iterMethod · 0.45

Tested by

no test coverage detected