Skip to content

Commit

Permalink
Added from scratch binary search implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 19, 2024
1 parent 28a61d6 commit c6a15c1
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/leetcode/binary_search.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
// pub fn search(numbers: Vec<i32>, target: i32) -> i32 {
// match numbers.binary_search(&target) {
// Ok(i) => i as i32,
// Err(_) => -1,
// }
// }

use std::cmp::Ordering;

pub fn search(numbers: Vec<i32>, target: i32) -> i32 {
match numbers.binary_search(&target) {
Ok(i) => i as i32,
Err(_) => -1,
let (mut left, mut right) = (0, numbers.len());
while left < right {
let mid = left + (right - left) / 2;
match numbers[mid].cmp(&target) {
Ordering::Equal => return mid as i32,
Ordering::Less => left = mid + 1,
Ordering::Greater => right = mid,
}
}
-1
}

#[cfg(test)]
Expand All @@ -11,11 +26,14 @@ mod tests {

#[test]
fn finds_element_index_when_it_exists() {
assert_eq!(4, search(vec![-1, 0, 3, 5, 9, 12], 9))
assert_eq!(4, search(vec![-1, 0, 3, 5, 9, 12], 9));
assert_eq!(0, search(vec![5], 5));
}

#[test]
fn negative_one_when_element_does_not_exist() {
assert_eq!(-1, search(vec![-1, 0, 3, 5, 9, 12], 20))
assert_eq!(-1, search(vec![-1, 0, 3, 5, 9, 12], 20));
assert_eq!(-1, search(vec![-1, 0, 3, 5, 9, 12], 2));
assert_eq!(-1, search(vec![5], -5))
}
}

0 comments on commit c6a15c1

Please sign in to comment.