I have data stored spread out (x and y in the example below) and I want to sort them relative to each other.
Is this somehow possible with the stdlib or do I need to write my own sorting algorithm?
fn sort_references<T: Ord>(arr: &mut [&mut T]) {
todo!();
// sort by writing to the underlying data, not swap pointers in array
}
#[test]
fn tests() {
let mut x = 2;
let mut y = 1;
sort_references(&mut [&mut x, &mut y]);
assert_eq!(x, 1);
assert_eq!(y, 2);
}
T is not necessarily Clone
The arrays are quite small (<50 elements) but dynamic in size
Incidentally by sorting the objects directly in the slice, the std implementation can move ranges of elements all at once with a memcpy. You would need reads and writes for each element.
So the ideal algorithm is probably different anyway.
Alternatively you could sort some wrapper that remembers source index and then figure out how to swap things around afterwards, but that doesn't seem any nicer to me. ↩︎