Add an example to show how to insert item to a sorted vec
This commit is contained in:
parent
6f70adcb18
commit
93839c3fb4
1 changed files with 14 additions and 0 deletions
|
@ -1364,6 +1364,20 @@ 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 = match s.binary_search(&num) {
|
||||
/// Ok(idx) => idx,
|
||||
/// Err(idx) => idx,
|
||||
/// };
|
||||
/// 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
|
||||
|
|
Loading…
Reference in a new issue