How to make this selection sort generic?

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);                                            
     }                                                                  
  }           

I want to make this code, now this code only works with Vec but I want this to make generic so it works on all datatypes.
I tried fn selection_sort<F: Ord>(arr: &[T])

but it says

error[E0507]: cannot move out of array[_], as array is a captured vari
able in an FnMut closure
--> selection_sort.rs:35:44
|
31 | fn selection_sort2<T: Ord>(array: &mut[T]) {
| ----- captured outer variable
...
35 | let min = (i..len).min_by_key(|x| array[*x])
| ^^^^^^^^^ move occurs beca
use array[_] has type T, which does not implement the Copy trait

your implementation relies on cheap copying when returning the key - so as a first step, you can write the same function with T: Ord + Copy and it should work.

As a second step, we can work on removing the Copy requirement.

Either:

A. Change from min_by_key to a min_by variant that uses a comparison function and doesn't need to return a key value. It's a bit more verbose, but should work the same way.
B. It works the same way with let min = (i..len).min_by_key(|x| &array[*x]).unwrap();, so that works fine as well (just insert the & there).

1 Like

Worked..! Thanks :heart_decoration:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.