MCPcopy Create free account
hub / github.com/IntegralPilot/rustc_codegen_jvm / binary_search

Function binary_search

tests/binary/binsearch/src/main.rs:3–21  ·  view source on GitHub ↗

Binary search for u32 slices. Returns `Some(index)` if `target` is found, or `None` otherwise.

(slice: &[u32], target: u32)

Source from the content-addressed store, hash-verified

1/// Binary search for u32 slices.
2/// Returns `Some(index)` if `target` is found, or `None` otherwise.
3pub fn binary_search(slice: &[u32], target: u32) -> Option<usize> {
4 let mut low = 0;
5 let mut high = slice.len();
6
7 while low < high {
8 // mid = floor((low + high) / 2) without overflow
9 let mid = low + (high - low) / 2;
10 let v = slice[mid];
11 if v < target {
12 low = mid + 1;
13 } else if v > target {
14 high = mid;
15 } else {
16 return Some(mid);
17 }
18 }
19
20 None
21}
22
23fn main() {
24 // demo array (must be sorted!)

Callers

nothing calls this directly

Calls 1

lenMethod · 0.80

Tested by

no test coverage detected