forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket_sort.rs
80 lines (68 loc) · 1.75 KB
/
bucket_sort.rs
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
80
/// Sort a slice using bucket sort algorithm.
///
/// Time complexity is `O(n + k)` on average, where `n` is the number of elements,
/// `k` is the number of buckets used in process.
///
/// Space complexity is `O(n + k)`, as it sorts not in-place.
pub fn bucket_sort(arr: &[usize]) -> Vec<usize> {
if arr.is_empty() {
return vec![];
}
let max = *arr.iter().max().unwrap();
let len = arr.len();
let mut buckets = vec![vec![]; len + 1];
for x in arr {
buckets[len * *x / max].push(*x);
}
for bucket in buckets.iter_mut() {
super::insertion_sort(bucket);
}
let mut result = vec![];
for bucket in buckets {
for x in bucket {
result.push(x);
}
}
result
}
#[cfg(test)]
mod tests {
use super::super::is_sorted;
use super::*;
#[test]
fn empty() {
let arr: [usize; 0] = [];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
#[test]
fn one_element() {
let arr: [usize; 1] = [4];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
#[test]
fn already_sorted() {
let arr: [usize; 3] = [10, 9, 105];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
#[test]
fn basic() {
let arr: [usize; 4] = [35, 53, 1, 0];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
#[test]
fn odd_number_of_elements() {
let arr: Vec<usize> = vec![1, 21, 5, 11, 58];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
#[test]
fn repeated_elements() {
let arr: Vec<usize> = vec![542, 542, 542, 542];
let res = bucket_sort(&arr);
assert!(is_sorted(&res));
}
}