Skip to content

Commit ba21a43

Browse files
author
Philip Tallo
committed
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 <[email protected]> Cleanup: Fixed failing tidy checks
1 parent a73ecb3 commit ba21a43

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/libcore/slice/mod.rs

+17
Original file line numberDiff line numberDiff line change
@@ -1362,6 +1362,23 @@ impl<T> [T] {
13621362
/// let r = s.binary_search(&1);
13631363
/// assert!(match r { Ok(1..=4) => true, _ => false, });
13641364
/// ```
1365+
///
1366+
/// Inserts a new element into already sorted array while maintaining sorted
1367+
/// order. Then asserts that the item was inserted correctly.
1368+
///
1369+
/// ```
1370+
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1371+
/// let num = 14;
1372+
///
1373+
/// match s.binary_search(&num) {
1374+
/// Ok(_) => {}
1375+
/// Err(pos) => {
1376+
/// s.insert(pos, num);
1377+
/// }
1378+
/// };
1379+
///
1380+
/// assert_eq!(s[10], num)
1381+
/// ```
13651382
#[stable(feature = "rust1", since = "1.0.0")]
13661383
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
13671384
where T: Ord

0 commit comments

Comments
 (0)