implemented Selection Sort

This commit is contained in:
jellyfishsh 2025-04-12 14:46:40 -07:00
parent 9965703278
commit a8623726ec

View File

@ -22,8 +22,11 @@ fn main() {
// so we can use it in our function // so we can use it in our function
let test_vector_string = format!("{:?}", test_vector); let test_vector_string = format!("{:?}", test_vector);
println!("Here are the values of the array, unsorted: {}", test_vector_string); println!("Here are the values of the array, unsorted: {}", test_vector_string);
//Now, sort it!
selection_sort(&mut test_vector);
let test_vector_string = format!("{:?}", test_vector);
println!("Here are the values of the array, sorted (ascending): {}", test_vector_string);
} }
@ -34,12 +37,11 @@ fn main() {
fn randomize_vector (vector : &mut Vec<i32>, size : u32) { fn randomize_vector (vector : &mut Vec<i32>, size : u32) {
//First clear the array //First clear the array
vector.clear(); vector.clear();
let mut rng = rand::rng(); let mut rng = rand::rng();
// Ranges are built into Rust! // Ranges are built into Rust!
// Nice that using underscores for useless stuff will work // Nice that using underscores for useless stuff will work
for _ in 0..size { for _ in 0..size {
// Fill vector with random values // Fill vector with random values
let random_number = rng.random_range(MIN_RANDOM..=MAX_RANDOM); let random_number = rng.random_range(MIN_RANDOM..=MAX_RANDOM);
vector.push(random_number); vector.push(random_number);
@ -49,9 +51,35 @@ fn randomize_vector (vector : &mut Vec<i32>, size : u32) {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn selection_sort(unsorted_array : &mut [i32]) { fn selection_sort(vector : &mut [i32]) {
//Creates the anonymous indexing value
let mut i : usize = 0;
while i < vector.len() {
//Keep track of the greatest value
let mut max_value = vector[i];
let mut max_index = i;
//Creates the anonymous indexing value
let mut j : usize = i;
while j < vector.len() {
if vector[j] > max_value {
//We make this the new greatest
max_value = vector[j];
max_index = j;
}
j += 1;
}
//Swap the values
let temp = vector[i];
vector[i] = max_value;
vector[max_index] = temp;
i += 1;
}
} }