
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort


Task

Sort an array (or list) of elements using the Selection sort algorithm.



It works as follows:

First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.



Its asymptotic complexity is    O(n2)    making it inefficient on large arrays.

Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.

No other sorting algorithm has less data movement.



References

   Rosetta Code:   O     (complexity).
   Wikipedia:   Selection sort.
   Wikipedia:   [Big O notation].


 
fn selection_sort(array: &mut [i32]) {
 
    let mut min;
 
    for i in 0..array.len() {
 
        min = i;
 
        for j in (i+1)..array.len() {
 
            if array[j] < array[min] {
                min = j;
            }
        }
 
        let tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;
    }
}
 
fn main() {
 
    let mut array = [ 9, 4, 8, 3, -5, 2, 1, 6 ];
    println!("The initial array is {:?}", array);
 
    selection_sort(&mut array);
    println!(" The sorted array is {:?}", array);
}
 