rust_sort/selection_sort.rs
1use super::Sortable;
2
3/// Selection sorts in-place, in ascending order, a mutable ref slice of type T: Sortable
4/// Selection Sort is not stable because it swaps non-adjacent elements.
5///
6/// Selection sort loops over an unsorted collection, finding the next minimum element,
7/// and swaps it with the current element. Repeating until all elements are in right order.
8///
9/// # Examples
10///
11/// ```
12/// use rust_sort::selection_sort::sort;
13///
14/// let mut arr = [3, 2, 1, 7, 9, 4, 1, 2];
15/// sort(&mut arr);
16/// assert_eq!(arr, [1, 1, 2, 2, 3, 4, 7, 9]);
17///
18/// ```
19pub fn sort<T: Sortable>(list: &mut [T]) {
20 let len = list.len();
21 if len <= 1 {
22 return;
23 }
24
25 for i in 0..(len - 1) {
26 let mut min = i;
27 for j in (i + 1)..len {
28 if list[j] < list[min] {
29 min = j
30 }
31 }
32 if min != i {
33 list.swap(i, min);
34 }
35 }
36}