Binary search for u32 slices. Returns `Some(index)` if `target` is found, or `None` otherwise.
(slice: &[u32], target: u32)
| 1 | /// Binary search for u32 slices. |
| 2 | /// Returns `Some(index)` if `target` is found, or `None` otherwise. |
| 3 | pub 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 | |
| 23 | fn main() { |
| 24 | // demo array (must be sorted!) |