Skip to content

Commit

Permalink
Rollup merge of rust-lang#63442 - lzutao:vec-bin-search-insert, r=Mar…
Browse files Browse the repository at this point in the history
…k-Simulacrum

Add an example to show how to insert item to a sorted vec

Closes rust-lang#61684
cc rust-lang#61742
r? @Mark-Simulacrum, @jonas-schievink
  • Loading branch information
Mark-Simulacrum committed Aug 11, 2019
2 parents c805a38 + 30ba4bd commit e16b12f
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1364,6 +1364,17 @@ impl<T> [T] {
/// let r = s.binary_search(&1);
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
///
/// If you want to insert an item to a sorted vector, while maintaining
/// sort order:
///
/// ```
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
/// let num = 42;
/// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
/// s.insert(idx, num);
/// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where T: Ord
Expand Down

0 comments on commit e16b12f

Please sign in to comment.