Binary Search Variant With Lower Bound (Rust)
Find the leftmost position where a sorted Rust slice can accept a target using a binary search lower bound.
Code
fn lower_bound(arr: &[i32], target: i32) -> usize {
let mut lo = 0usize;
let mut hi = arr.len();
while lo < hi {
let mid = (lo + hi) / 2;
if arr[mid] < target { lo = mid + 1; } else { hi = mid; }
}
lo
}
fn main() {
let arr = [1, 2, 2, 3, 4, 6];
assert_eq!(lower_bound(&arr, 2), 1);
assert_eq!(lower_bound(&arr, 5), 5);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.