Sorting a vector of integers is straight forward as demonstrated here. However, a vector of floats is more complicated due to potential NaN's and floating point operations.
I would like to "combine" the two methods below to get the indicies that would sort a vector of floats, without sorting the actual input vector.
// returns the indices that would sort a vector of ints
fn argsort<T: Ord>(data: &[T]) -> Vec<usize> {
let mut indices = (0..data.len()).collect::<Vec<_>>();
indices.sort_by_key(|&i| &data[i]);
indices
}
and
use std::cmp::Ordering;
// returns a sorted vector of floats that may contain NaNs, with NaNs at the end
fn sort(arr: &Vec<f64>) -> Vec<f64> {
let mut out = arr.clone();
out.sort_by(|&a, &b| {
match (a.is_nan(), b.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.partial_cmp(&b).unwrap(),
}
});
return out;
}
How can I return a vector of usize
indices that would sort an input vector of floats containing NaNs?