1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
pub fn bucket_sort<H, F, T>(arr: &mut [T], hasher: F)
where
H: Ord,
F: Fn(&T) -> H,
T: Ord + Clone,
{
let mut buckets: Vec<Bucket<H, T>> = Vec::new();
for value in arr.iter() {
let hash = hasher(&value);
let value = value.clone();
match buckets.binary_search_by(|bucket| bucket.hash.cmp(&hash)) {
Ok(index) => buckets[index].values.push(value),
Err(index) => buckets.insert(index, Bucket::new(hash, value)),
}
}
let ret = buckets
.into_iter()
.flat_map(|mut bucket| {
bucket.values.sort();
bucket.values
})
.collect::<Vec<T>>();
arr.clone_from_slice(&ret);
}
struct Bucket<H, T> {
hash: H,
values: Vec<T>,
}
impl<H, T> Bucket<H, T> {
pub fn new(hash: H, value: T) -> Bucket<H, T> {
Bucket {
hash,
values: vec![value],
}
}
}
#[cfg(test)]
mod base {
use super::*;
fn bucket_sort_(arr: &mut [i32]) {
bucket_sort(arr, |int| int / 4);
}
base_cases!(bucket_sort_);
}
#[cfg(test)]
mod stability {
use super::*;
fn bucket_sort_(arr: &mut [(i32, i32)]) {
bucket_sort(arr, |t| t.0 / 4);
}
stability_cases!(bucket_sort_);
}