1#![feature(is_sorted)]
2#![feature(exclusive_range_pattern)]
3
4pub type FnMustSwap<T> = fn(a: &T, b: &T) -> bool;
5
6pub fn asc<T>(a: &T, b: &T) -> bool where T: PartialOrd {
7 a > b
8}
9
10pub fn desc<T>(a: &T, b: &T) -> bool where T: PartialOrd {
11 a < b
12}
13
14pub trait SelectionSort<T> {
15 fn selection_sort(&mut self);
16 fn selection_sort_by(&mut self, by: FnMustSwap<T>);
17}
18
19impl<T> SelectionSort<T> for Vec<T> where T: PartialOrd {
20 fn selection_sort(&mut self) {
21 self.selection_sort_by(asc)
22 }
23
24 fn selection_sort_by(&mut self, by: FnMustSwap<T>) {
25 let size = self.len();
26 for i in 0..size {
27 let mut mm_index = i;
28 for j in (i + 1)..size {
29 if by(&self[mm_index], &self[j]) {
30 mm_index = j;
31 }
32 }
33 self.swap(i, mm_index);
34 }
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use crate::{SelectionSort, desc};
41
42 #[test]
43 fn test_selection_sort() {
44 let mut input: Vec<u32> = vec![];
45 input.reverse();
46 input.selection_sort();
47 assert!(input.is_sorted());
48
49 let mut input: Vec<u32> = vec![1];
50 input.reverse();
51 input.selection_sort();
52 assert!(input.is_sorted());
53
54 let mut input: Vec<u32> = vec![2, 1];
55 input.reverse();
56 input.selection_sort();
57 assert!(input.is_sorted());
58
59 let mut input: Vec<u32> = vec![0, 1, 2, 3];
60 input.reverse();
61 input.selection_sort();
62 println!("{:?}", input);
63 assert!(input.is_sorted());
64
65 let mut input: Vec<u32> = vec![1, 1, 2, 3];
66 input.reverse();
67 input.selection_sort();
68 println!("{:?}", input);
69 assert!(input.is_sorted());
70
71 let mut input: Vec<u32> = vec![1, 1, 2, 3];
72 input.selection_sort_by(desc);
73 input.reverse();
74 println!("{:?}", input);
75 assert!(input.is_sorted());
76 }
77}