6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rust] argsort

Posted at

Rust の Vec<T> (正確には Deref<Target = [T]>) は sortsort_unstable といったメソッドを持ちますが, 配列そのものは変更せずソートした順のインデックスの配列が欲しいことがあります. そんなときはこちら:

fn argsort<T: Ord>(v: &[T]) -> Vec<usize> {
    let mut idx = (0..v.len()).collect::<Vec<_>>();
    idx.sort_unstable_by(|&i, &j| v[i].cmp(&v[j]));
    idx
}

最も効率的か若干自信がないですが... 安定ソートが欲しい場合は unstable を外してください.

使用例:

fn main() {
    let mut v = [-5, 4, 1, -3, 2];

    let idx = argsort(&v);

    for i in idx.into_iter() {
        println!("v[{}] = {}", i, v[i]);
    }
}
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?