Table of content

Selection sort in Rust

Selection sort is one of the easiest to implement entry sorting methods. It divides the data into sorted piles and unsorted piles, each time finding the maximum/minimum from the unsorted pile and adding it to the sorted pile.

The characteristics of Selection sort are as follows:
  • One of the simplest sorting methods.
  • Sorting small data sequences is more efficient.
  • Unstable ordering: After sorting, the relative position of elements of the same key value may change.
  • In-place sorting: no additional storage space to sort.
  • The data is divided into a sorted pile and an unsorted pile.
  • Find the minimum from the unsorted pile.
  • Replace the minimum element with the first element of the unsorted pile.
  • Repeat steps 2 - 3 until the sort is complete.

Note that this naïve's selection sort is actually an unstable sort.

/// Selection sort.

pub fn selection_sort(arr: &mut [i32]) { let len = arr.len(); // Rust would skip iteration if lower bound >= upper bound. // Hence, no need to `len - 1`. for i in 0..len { let mut temp = i; for j in (i + 1)..len { if arr[temp] > arr[j] { temp = j; } } arr.swap(i, temp); } }


mod base { use super::*; base_cases!(selection_sort); }

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions