-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
bucket_sort.rs
87 lines (75 loc) · 2.16 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
81
82
83
84
85
86
87
/// 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::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn empty() {
let arr: [usize; 0] = [];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let arr: [usize; 1] = [4];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn already_sorted() {
let arr: [usize; 3] = [10, 19, 105];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn basic() {
let arr: [usize; 4] = [35, 53, 1, 0];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn odd_number_of_elements() {
let arr: [usize; 5] = [1, 21, 5, 11, 58];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn repeated_elements() {
let arr: [usize; 4] = [542, 542, 542, 542];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}