7
\$\begingroup\$

I am just trying to use Rust so I will be thankful for all remarks and corrections:

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 values = [ 5, 8, 4, 1, 7, 2, 3, 6 ];
    println!("Hello, world! The value is {:?}", values);

    selection_sort(&mut values);
    println!("Hello, world! The value is {:?}", values);
}
\$\endgroup\$
6
\$\begingroup\$

You could use min_by_key to find the minimum's index and the method swap defined in slices:

fn selection_sort(array: &mut [i32]) {
    let len = array.len();
    for i in 0..len {
        let min = (i..len).min_by_key(|x| array[*x])
                          .unwrap();
        array.swap(min, i);
    }
}
\$\endgroup\$
5
\$\begingroup\$
  1. No newlines after an opening brace but before the code starts
  2. Use spaces around binary operators like +.
  3. Use swap. This prevents you from needing to make a copy/clone of the variable.
  4. Declare variables in as small a scope as possible. There's no reason to declare min outside of the array.
  5. I'd use more iterator methods like enumerate to avoid array indexing, which incurs a small penalty for out-of-bounds checking.
fn selection_sort(array: &mut [i32]) {
    for i in 0..array.len() {
        let min_idx = array[i..].iter()
            .enumerate()
            .min_by_key(|&(_, v)| v)
            .map(|(i, _)| i)
            .unwrap_or(0);

        array.swap(i, min_idx + i);
    }
}

As a follow-up, I'd challenge you to make this algorithm work with more than just i32 types!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.