math_ops/
sort.rs

1//! Sorting methods for `Vector<T>`.
2
3use num_traits::{Float, ToPrimitive};
4use crate::vector::Vector;
5
6/// Trait providing sorting methods for `Vector<T>`.
7pub trait SortOps<T> {
8  /// Returns a new sorted vector without modifying the original.
9  fn sorted(&self) -> Vector<T>;
10
11  /// Sorts the vector in place.
12  fn sort_in_place(&mut self);
13}
14
15impl<T> SortOps<T> for Vector<T>
16where
17  T: Float + ToPrimitive + Copy + PartialOrd,
18{
19  fn sorted(&self) -> Vector<T> {
20    let mut sorted = self.clone();
21    sorted.sort_in_place();
22    sorted
23  }
24
25  fn sort_in_place(&mut self) {
26    self.0.sort_by(|a, b| {
27      match (a.partial_cmp(b), a.is_nan(), b.is_nan()) {
28        (Some(ordering), _, _) => ordering,
29        (None, false, true) => std::cmp::Ordering::Less,  // Keep `a` before `b` when `b` is NaN
30        (None, true, false) => std::cmp::Ordering::Greater, // Move `a` after `b` when `a` is NaN
31        _ => std::cmp::Ordering::Equal,  // Both are NaN, keep equal
32      }
33    });
34  }
35}