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);
}What the code does
Binary Search Variant With Lower Bound (Rust) reduces to the functions lower_bound and main.
Iteration happens inside while lo < hi — everything outside it runs once.
Applying it
The primary signature is fn lower_bound(arr: &[i32], target: i32) -> usize
The entry point wires lower_bound together — run it once and the whole demo flows.
Statements that matter
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
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- How do you run Binary Search Variant With Lower Bound (Rust)?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.