Skip to content

Commit 18431b6

Browse files
authored
Rollup merge of #102507 - scottmcm:more-binary-search-docs, r=m-ou-se
More slice::partition_point examples After seeing the discussion of `binary_search` vs `partition_point` in #101999, I thought some more example code could be helpful.
2 parents d2644e5 + 5b9a02a commit 18431b6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

library/core/src/slice/mod.rs

+32
Original file line numberDiff line numberDiff line change
@@ -2359,6 +2359,28 @@ impl<T> [T] {
23592359
/// assert!(match r { Ok(1..=4) => true, _ => false, });
23602360
/// ```
23612361
///
2362+
/// If you want to find that whole *range* of matching items, rather than
2363+
/// an arbitrary matching one, that can be done using [`partition_point`]:
2364+
/// ```
2365+
/// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2366+
///
2367+
/// let low = s.partition_point(|x| x < &1);
2368+
/// assert_eq!(low, 1);
2369+
/// let high = s.partition_point(|x| x <= &1);
2370+
/// assert_eq!(high, 5);
2371+
/// let r = s.binary_search(&1);
2372+
/// assert!((low..high).contains(&r.unwrap()));
2373+
///
2374+
/// assert!(s[..low].iter().all(|&x| x < 1));
2375+
/// assert!(s[low..high].iter().all(|&x| x == 1));
2376+
/// assert!(s[high..].iter().all(|&x| x > 1));
2377+
///
2378+
/// // For something not found, the "range" of equal items is empty
2379+
/// assert_eq!(s.partition_point(|x| x < &11), 9);
2380+
/// assert_eq!(s.partition_point(|x| x <= &11), 9);
2381+
/// assert_eq!(s.binary_search(&11), Err(9));
2382+
/// ```
2383+
///
23622384
/// If you want to insert an item to a sorted vector, while maintaining
23632385
/// sort order, consider using [`partition_point`]:
23642386
///
@@ -3787,6 +3809,16 @@ impl<T> [T] {
37873809
/// assert!(v[i..].iter().all(|&x| !(x < 5)));
37883810
/// ```
37893811
///
3812+
/// If all elements of the slice match the predicate, including if the slice
3813+
/// is empty, then the length of the slice will be returned:
3814+
///
3815+
/// ```
3816+
/// let a = [2, 4, 8];
3817+
/// assert_eq!(a.partition_point(|x| x < &100), a.len());
3818+
/// let a: [i32; 0] = [];
3819+
/// assert_eq!(a.partition_point(|x| x < &100), 0);
3820+
/// ```
3821+
///
37903822
/// If you want to insert an item to a sorted vector, while maintaining
37913823
/// sort order:
37923824
///

0 commit comments

Comments
 (0)