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

Function bucket_sort

code/chapter06/bucket_sort.rs:21–46  ·  view source on GitHub ↗

桶排序,Debug 特性是为了打印 T

(nums: &mut [T], hasher: F)

Source from the content-addressed store, hash-verified

19
20// 桶排序,Debug 特性是为了打印 T
21fn bucket_sort<H, T, F>(nums: &mut [T], hasher: F)
22 where H: Ord,
23 T: Ord + Clone + Debug,
24 F: Fn(&T) -> H {
25 let mut buckets: Vec<Bucket<H, T>> = Vec::new();
26
27 for value in nums.iter() {
28 let hasher = hasher(&value);
29
30 // 对桶中数据二分搜索并排序
31 match buckets.binary_search_by(|bucket| bucket.hasher.cmp(&hasher)) {
32 Ok(index) => buckets[index].values.push(value.clone()),
33 Err(index) => buckets.insert(index, Bucket::new(hasher, value.clone())),
34 }
35 }
36
37 // 拆桶,将所有排序数据融合到一个 Vec
38 let ret = buckets.into_iter().flat_map(|mut bucket| {
39 bucket.values.sort();
40 bucket.values
41 }).collect::<Vec<T>>();
42
43 nums.clone_from_slice(&ret);
44
45 // println!("sorted nums: {:?}", ret);
46}
47
48fn main() {
49 let mut nums = [54,32,99,18,75,31,43,56,21,22,1,100];

Callers 1

mainFunction · 0.70

Calls 6

iterMethod · 0.45
cmpMethod · 0.45
pushMethod · 0.45
insertMethod · 0.45
into_iterMethod · 0.45
sortMethod · 0.45

Tested by

no test coverage detected