Skip to content

Commit

Permalink
Add rust binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
indy256 committed Jul 7, 2024
1 parent b2d2c6d commit ca77395
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ path = "structures/fenwick_tree.rs"
[[bin]]
name = "persistent_tree"
path = "structures/persistent_tree.rs"

[[bin]]
name = "binary_search"
path = "misc/binary_search.rs"
35 changes: 35 additions & 0 deletions rust/misc/binary_search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// invariant: f[lo] == false, f[hi] == true
pub fn binary_search_first_true<F>(f: F, from_inclusive: i32, to_inclusive: i32) -> i32
where
F: Fn(i32) -> bool,
{
let mut lo = from_inclusive - 1;
let mut hi = to_inclusive + 1;
while hi - lo > 1 {
let mid = (lo + hi) / 2;
if !f(mid) {
lo = mid;
} else {
hi = mid;
}
}
hi
}

#[cfg(test)]
mod tests {
use rstest::rstest;
use crate::binary_search_first_true;

#[rstest]
#[case(100, 0)]
#[case(100, 1)]
#[case(100, 50)]
#[case(100, 100)]
fn basic_test(
#[case] n: i32,
#[case] pos: i32,
) {
assert_eq!(binary_search_first_true(|i| { i >= pos }, 0, n), pos);
}
}

0 comments on commit ca77395

Please sign in to comment.