對整數向量進行排序很簡單,如此處所示。但是,由于潛在的 NaN 和浮點運算,浮點向量更加復雜。
我想“組合”下面的兩種方法來獲得對浮點向量進行排序的索引,而不對實際輸入向量進行排序。
// 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
}
和
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;
}
如何回傳一個usize索引向量來對包含 NaN 的浮點輸入向量進行排序?
uj5u.com熱心網友回復:
我不確定我是否理解你的問題。您的第二個片段似乎幾乎回答了這個問題。這是您要尋找的答案嗎?
fn sort(arr: &Vec<f64>) -> Vec<usize> {
let mut out = (0..arr.len()).collect::<Vec<usize>>();
out.sort_by(|&a_idx, &b_idx| {
let a = arr[a_idx];
let b = arr[b_idx];
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(),
}
});
out
}
uj5u.com熱心網友回復:
// construct a tuple vector from the floats, the tuple being (index,float)
let mut with_indices = arr.clone().into_iter().enumerate()
.map(|index,value| (index,value)).collect::<Vec<(usize,f64)>>();
// sort the tuple vector by float
with_indices.sort_by(|&a, &b| {
match (a.1.is_nan(), b.1.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.1.partial_cmp(&b.1).unwrap(),
}
});
// extract the sorted indices from the sorted tuple vector
let stored_indices = with_indices.into_iter().map(|(index,value)| index)
.collect::<Vec<usize>>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524704.html
標籤:排序锈浮点
