This post is about the sorting algorithm Selection Sort in Rust using recursion and iteration.
Rust Selection Sort Using Recursion
The sample Selection Sort codes in this post that use recursion have 3 functions. The first function bootstraps the recursive function.
1 2 3 4 | // Bootstrap recursive function fn selection_sort_recursive(param_int_array:&mut [i32]) { selection_sort_recursive_process(param_int_array, 0); } |
The second function is the actual function for the Selection Sort that uses recursion. It runs the function swap function to switch values between two variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | fn selection_sort_recursive_process(param_int_array: &mut [i32], index: usize) { let arr_length = param_int_array.len(); let mut min = index; let mut j = index + 1; while j < arr_length { if param_int_array[j] < param_int_array[min] { min = j; } j+=1; } swap(param_int_array, min, index); if index + 1 < arr_length { selection_sort_recursive_process(param_int_array, index + 1) } } |
The swap function is as follows. It accepts a mutable array of i32, the indexes of elements whose values the codes to swap.
1 2 3 4 5 | fn swap(param_int_array: &mut [i32], i: usize, j: usize ) { let temp = param_int_array[i]; param_int_array[i] = param_int_array[j]; param_int_array[j] = temp; } |
Below is an example of codes that use our bootstrap function in the main function in Rust.
1 2 3 4 5 | fn main() { let mut int_values_array:[i32; 11] = [1, 0, 9, 8, 5, 6,7 , 4, 3, 2, 1]; selection_sort_recursive(&mut int_values_array); println!("{:?}", int_values_array); } |
The codes output the following.
1 | [0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Rust Selection Sort Using Iteration
The Selection Sort codes that use iteration have a single function that accepts a mutable reference to an array of i32‘s with any length and returns nothing. Note that we are using nested loops for this kind of sorting. The outer loop iterates over an array of i32’s, while the inner loop iterates a subset of the same array for each i32.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | fn selection_sort_iterative(param_int_array: &mut [i32]) { let mut j = 0; let arr_length = param_int_array.len(); while j < arr_length { let mut min = j; let mut i = j + 1; while i < arr_length { if param_int_array[i] < param_int_array[min] { min = i; } i+=1; } if min != j { let temp = param_int_array[j]; param_int_array[j] = param_int_array[min]; param_int_array[min] = temp; } j+=1; } } |
Below are example codes to run the iterative function.
1 2 3 4 5 | fn main() { let mut int_values_array:[i32; 11] = [1, 0, 9, 8, 5, 6,7 , 4, 3, 2, 1]; selection_sort_iterative(&mut int_values_array); println!("{:?}", int_values_array); } |
The codes output the following.
1 | [0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Tested with Rust 1.52.1.
Other Algorithms in Rust
For more algorithms in Rust, please go to the Algorithms In Codes page.