-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselection_sort.rs
60 lines (55 loc) · 1.42 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Selection Sort
*
* Selection sort is another sorting algorithm, which compares smallest of all
* values and and put it in the first position. Similarly, after swapping value,
* it will find out second most smallest value and swap it with second item in
* the array.
*
* Unlike bubble sort, the sorting will be done from the beginning.
*
* Example:
*
* 4 2 9 0 7 5 1 <- Swap 4 and 0
* ^ ^
* [0] 2 9 4 7 5 1 <- 0 is sorted
* [0] 2 9 4 7 5 1 <- Swap 2 and 1
* ^ ^
* ...
* Swap values until all values are sorted
**/
fn selection_sort(array: &mut [isize]) -> &mut [isize] {
for i in 0..array.len() {
let mut smallest = i;
for j in i..array.len() {
if array[smallest] > array[j] {
smallest = j;
}
}
if smallest != i {
print!(
"Swapping {} and {} from {:?} -> ",
array[smallest], array[i], array
);
array.swap(i, smallest);
println!("{:?}", array)
}
}
array
}
fn main() {
let mut unsorted = [4, 2, 9, 0, 7, 5, 1];
let sorted = selection_sort(unsorted.as_mut());
println!("Sorted data: {:?}", sorted);
}
#[cfg(test)]
mod tests {
use crate::selection_sort;
#[test]
fn sort_success() {
assert_eq!(
selection_sort([1, 2, 5, 4, 3, 6].as_mut()),
[1, 2, 3, 4, 5, 6]
)
}
}