Selection sort
Selection sort is a straightforward, iterative algorithm that repeatedly identifies and relocates the smallest unsorted element within a portion of the array, moving it to the front of the remaining unsorted section until the entire array is in order:
use super::AlgorithmState;
/// Sorts the slice using selection sort algorithm and the comparison function `is_less` passed as
/// argument.
fn selection_sort<T, F>(v: &mut [T], mut is_less: F)
where
F: FnMut(&T, &T) -> bool,
{
for i in 0..v.len() {
let mut k = i;
for j in i + 1..v.len() {
if is_less(&v[j], &v[k]) {
k = j;
}
}
v.swap(i, k);
Is easy to see from the code that the algorithm for each from to there is only one swap and comparisons, so the total is:
Which is of complexity in terms of number of comparisons. Here is an animated image of the visualization of how the algorithm works:
The full source code can be found here