Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the indices that would sort a Vec?

Tags:

sorting

rust

I want to get the indices that would sort a Vec in Rust. Effectively, I want argsort() from numpy.

For example:

let v = vec![1, 7, 4, 2];
let i = argsort(&v);
assert_eq!(i, &[0, 3, 2, 1]);
like image 794
Michael Hall Avatar asked Dec 13 '25 19:12

Michael Hall


1 Answers

Not sure if there's something pre-made for this, but its simple enough to implement yourself with .sort_by_key():

pub fn argsort<T: Ord>(data: &[T]) -> Vec<usize> {
    let mut indices = (0..data.len()).collect::<Vec<_>>();
    indices.sort_by_key(|&i| &data[i]);
    indices
}

See it working on the playground.

like image 114
kmdreko Avatar answered Dec 15 '25 12:12

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!