jshholland / worstsort
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
fn bubblesort<T: Ord>(l: &mut [T]) {
for i in 1..l.len() {
for j in 0..l.len() - i {
if l[j + 1] < l[j] {
l.swap(j + 1, j);
}
}
}
}
fn permutations<T: Clone>(l: &[T]) -> Vec<Vec<T>> {
if l.len() <= 1 {
return vec![l.to_vec()];
}
let mut res = Vec::new();
for i in 0..l.len() {
let mut lcopy = l.to_vec();
lcopy.remove(i);
let p = permutations(&lcopy);
for perm in p {
let mut fullperm = vec![l[i].clone()];
fullperm.extend(perm);
res.push(fullperm);
}
}
res
}
pub fn badsort<T: Ord + Clone>(k: usize, l: &mut [T]) {
if k == 0 {
bubblesort(l);
} else {
let mut p = permutations(l);
badsort(k - 1, &mut p);
l.clone_from_slice(&p[0]);
}
}
pub fn worstsort<T, F>(l: &mut [T], f: F)
where
T: Ord + Clone,
F: FnOnce(usize) -> usize,
{
badsort(f(l.len()), l);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn badsort_zero() {
let mut unsorted = vec![8, 3, 5];
badsort(0, &mut unsorted);
assert_eq!(unsorted, vec![3, 5, 8]);
}
#[test]
fn worstsort_id() {
let mut unsorted = vec![8, 3, 5];
worstsort(&mut unsorted, |n| n);
assert_eq!(unsorted, vec![3, 5, 8]);
}
#[test]
fn worstsort_zero() {
let mut unsorted = vec![8, 3, 5];
worstsort(&mut unsorted, |_| 0);
assert_eq!(unsorted, vec![3, 5, 8]);
}
}