Skip to content

Commit

Permalink
Added binary search solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 19, 2024
1 parent 76d4944 commit 28a61d6
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ programming challenges completed in other languages.
- [Final Prices After Discounts](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop)
- [Valid Palindrome](https://leetcode.com/problems/valid-palindrome)
- [Roman to Integer](https://leetcode.com/problems/roman-to-integer)
- [Binary Search](https://leetcode.com/problems/binary-search)

#### Medium

Expand Down
21 changes: 21 additions & 0 deletions src/leetcode/binary_search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub fn search(numbers: Vec<i32>, target: i32) -> i32 {
match numbers.binary_search(&target) {
Ok(i) => i as i32,
Err(_) => -1,
}
}

#[cfg(test)]
mod tests {
use super::*;

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

#[test]
fn negative_one_when_element_does_not_exist() {
assert_eq!(-1, search(vec![-1, 0, 3, 5, 9, 12], 20))
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,4 @@ mod xor_subarray;
mod zero_or_one;
mod zigzag_conversion;
mod valid_sudoku;
mod binary_search;

0 comments on commit 28a61d6

Please sign in to comment.