From ba21a436bbaa295e5d3c775489499c34eeee5aaf Mon Sep 17 00:00:00 2001 From: Philip Tallo Date: Tue, 11 Jun 2019 13:12:03 -0400 Subject: [PATCH 1/2] Updated Binary Search docs to show how to insert into an already sorted list Resolves: #61684 Apply suggestions from code review Co-Authored-By: Jonas Schievink Cleanup: Fixed failing tidy checks --- src/libcore/slice/mod.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 0e782bef39dd8..40dd0a48a4df5 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1362,6 +1362,23 @@ impl [T] { /// let r = s.binary_search(&1); /// assert!(match r { Ok(1..=4) => true, _ => false, }); /// ``` + /// + /// Inserts a new element into already sorted array while maintaining sorted + /// order. Then asserts that the item was inserted correctly. + /// + /// ``` + /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let num = 14; + /// + /// match s.binary_search(&num) { + /// Ok(_) => {} + /// Err(pos) => { + /// s.insert(pos, num); + /// } + /// }; + /// + /// assert_eq!(s[10], num) + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn binary_search(&self, x: &T) -> Result where T: Ord From f4bb9b389e9e4942153dafb24d277f1c601859d3 Mon Sep 17 00:00:00 2001 From: Philip Tallo Date: Wed, 10 Jul 2019 14:42:25 -0400 Subject: [PATCH 2/2] change match in binary search docs to if let --- src/libcore/slice/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 40dd0a48a4df5..4838cf33d354f 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1370,11 +1370,9 @@ impl [T] { /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; /// let num = 14; /// - /// match s.binary_search(&num) { - /// Ok(_) => {} - /// Err(pos) => { - /// s.insert(pos, num); - /// } + /// let idx = s.binary_search(&num); + /// if let Ok(idx) | Err(idx) { + /// s.insert(idx, num) /// }; /// /// assert_eq!(s[10], num)