Sort by column for ndarray

50 Views Asked by At

In rust, how do you efficiently sort an ndarray::Array2 by a particular column?

I am trying to sort an Array2 by a particular column of values, either ascending or descending.

1

There are 1 best solutions below

2
frankenapps On

Here is a simple solution using Vec::sort:

use ndarray::Array2;

fn main() {
    let mut arr2 = Array2::<i32>::from(vec![[1,2,4,3], [3,4,1,9], [4,7,2,9]]);

    for mut column in arr2.rows_mut() {
        let mut vec = column.to_vec();
        vec.sort();
        
        for j in 0..column.shape()[0] {
            column[j] = vec[j];
        }
    }
    
    println!("{:#?}", arr2);
}

Here is the link to RustExplorer.

If you want to get rid of the extra Vec, I think you would have to implement the sort algorithm (like Mergesort yourself).