Last active
September 9, 2022 12:58
-
-
Save MikuroXina/68a41e0d4e493a4604b76c0b6fd21659 to your computer and use it in GitHub Desktop.
Binary-search with given function in Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::cmp::Ordering; | |
| pub fn binary_search(max: usize, mut f: impl FnMut(usize) -> Ordering) -> Result<usize, usize> { | |
| let mut left = 0; | |
| let mut right = max; | |
| while left < right { | |
| let mid = left + (right - left) / 2; | |
| match f(mid) { | |
| Ordering::Less => left = mid + 1, | |
| Ordering::Greater => right = mid - 1, | |
| Ordering::Equal => return Ok(mid), | |
| } | |
| } | |
| Err(left) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment