forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.rs
45 lines (40 loc) · 980 Bytes
/
selection_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
pub fn selection_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
for left in 0..len {
let mut smallest = left;
for right in (left + 1)..len {
if arr[right] < arr[smallest] {
smallest = right;
}
}
arr.swap(smallest, left);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let mut res = vec!["d", "a", "c", "b"];
selection_sort(&mut res);
assert_eq!(res, vec!["a", "b", "c", "d"]);
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
selection_sort(&mut res);
assert_eq!(res, vec![]);
}
#[test]
fn one_element() {
let mut res = vec!["a"];
selection_sort(&mut res);
assert_eq!(res, vec!["a"]);
}
#[test]
fn pre_sorted() {
let mut res = vec!["a", "b", "c"];
selection_sort(&mut res);
assert_eq!(res, vec!["a", "b", "c"]);
}
}