How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Rust programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Rust programming language
Table of Contents
Problem Statement
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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Rust programming language
Source code in the rust programming language
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);
}
fn selection_sort<T: std::cmp::PartialOrd>(arr: &mut [T]) {
for i in 0 .. arr.len() {
let unsorted = &mut arr[i..];
let mut unsorted_min: usize = 0;
for (j, entry) in unsorted.iter().enumerate() {
if *entry < unsorted[unsorted_min] {
unsorted_min = j;
}
}
unsorted.swap(0, unsorted_min);
}
}
You may also check:How to resolve the algorithm Hash from two arrays step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Rename a file step by step in the Objective-C programming language
You may also check:How to resolve the algorithm File input/output step by step in the Wren programming language
You may also check:How to resolve the algorithm Faulhaber's formula step by step in the Sidef programming language
You may also check:How to resolve the algorithm Plasma effect step by step in the C programming language