Sort Vec by another Vec

I don't know if this has been comprehensively addressed here... I'd like to sort a Vec by another Vec.

A quick google search leads to this post. But I don't really want to use a whole crate if I can get away with it.

Is there an optimal way to do this? Or an idiomatic one?

e.g.

// Vec<usize>
let order = vec![2, 0, 1, 3, 4];
// Vec<u8>
let seq = vec![b'G', b'A', b'C', b'T', b'A'];

// ordering magic here...

// output
// [A, C, G, T, A]

Thanks!
M

Is order supposed to contain the indexes of the final positions of the elements in seq or can it be anything and you need to actually sort it?

order contains the indexes of the final positions, yes!

Here's one solution copied from the reorder crate:

let mut order: Vec<usize> = vec![2, 0, 1, 3, 4];
let mut seq: Vec<char> = vec!['G', 'A', 'C', 'T', 'A'];

for i in 0..seq.len() {
    let mut target = order[i];

    while target != i {
        order.swap(i, target);
        seq.swap(i, target);

        target = order[i];
    }
}

println!("{:?}", seq);
2 Likes

Thanks!

1 Like

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.