From f0a1a0c0ceeee9f6e2ec51d2b93f14f50ad7dcd0 Mon Sep 17 00:00:00 2001 From: Vincent Mutolo Date: Tue, 1 Dec 2020 14:53:22 -0500 Subject: [PATCH] Add Vector::insert_ord_by method --- src/vector/mod.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/vector/mod.rs b/src/vector/mod.rs index 7d54de1..6b9ffd4 100644 --- a/src/vector/mod.rs +++ b/src/vector/mod.rs @@ -1461,6 +1461,43 @@ impl Vector { } } + /// Insert an element into a sorted vector using a comparator function. + /// + /// Insert an element into a vector in sorted order using the given + /// comparator function, assuming the vector is already in sorted order. + /// + /// Time: O(log n) + /// + /// # Examples + /// + /// ``` + /// # #[macro_use] extern crate im; + /// # use im::vector::Vector; + /// use std::cmp::Ordering; + /// + /// fn reverse_cmp(x: &u8, y: &u8) -> Ordering { + /// match x.cmp(&y) { + /// Ordering::Equal => Ordering::Equal, + /// Ordering::Greater => Ordering::Less, + /// Ordering::Less => Ordering::Greater, + /// } + /// } + /// + /// let mut vec: Vector = vector![9, 8, 7, 3, 2, 1]; + /// vec.insert_ord_by(5, reverse_cmp); + /// assert_eq!(vector![9, 8, 7, 5, 3, 2, 1], vec); + /// ``` + pub fn insert_ord_by(&mut self, item: A, mut f: F) + where + A: Ord, + F: FnMut(&A, &A) -> Ordering, + { + match self.binary_search_by(|scan_item| f(scan_item, &item)) { + Ok(index) => self.insert(index, item), + Err(index) => self.insert(index, item), + } + } + /// Sort a vector. /// /// Time: O(n log n)