Skip to content

Instantly share code, notes, and snippets.

@JosephTLyons
Last active February 2, 2020 16:58
Show Gist options
  • Save JosephTLyons/17e5ddf80460d36be0cf0f5f5e00e9a5 to your computer and use it in GitHub Desktop.
Save JosephTLyons/17e5ddf80460d36be0cf0f5f5e00e9a5 to your computer and use it in GitHub Desktop.
binary_search in Rust
use std::cmp::Ordering;
#[allow(dead_code)]
fn binary_search<T: std::cmp::Ord>(n: T, array: &[T]) -> Option<usize> {
if !array.is_empty() {
let mut lower_bound = 0;
let mut upper_bound = array.len() - 1;
let mut midway_point;
while lower_bound <= upper_bound {
midway_point = (lower_bound + upper_bound) / 2;
match n.cmp(&array[midway_point]) {
Ordering::Equal => return Some(midway_point),
Ordering::Greater => lower_bound = midway_point + 1,
Ordering::Less => upper_bound = midway_point - 1,
}
}
}
None
}
#[test]
fn empty_array() {
assert_eq!(None, binary_search(3, &[]));
}
#[test]
fn one_value_in_array() {
assert_eq!(Some(0), binary_search(27, &[27]));
}
#[test]
fn value_in_array_beginning() {
assert_eq!(Some(0), binary_search(3, &[3, 5, 9, 15, 36]));
}
#[test]
fn value_in_array_middle() {
assert_eq!(Some(3), binary_search(15, &[3, 5, 9, 15, 36]));
}
#[test]
fn value_in_array_end() {
assert_eq!(Some(4), binary_search(36, &[3, 5, 9, 15, 36]));
}
#[test]
fn multiple_values_in_array() {
assert_eq!(
Some(6),
binary_search(13, &[3, 9, 10, 11, 12, 13, 13, 13, 36])
);
}
#[test]
fn value_not_in_array() {
assert_eq!(None, binary_search(14, &[3, 5, 9, 15, 36]));
}
#[test]
fn negative_value_in_array() {
assert_eq!(Some(1), binary_search(-121, &[-340, -121, 9, 43, 56, 3300]));
}
#[test]
fn negative_value_not_in_array() {
assert_eq!(None, binary_search(-93, &[-340, -121, 9, 43, 56, 3300]));
}
#[test]
fn check_all_elements_in_array() {
let values: &[i32] = &[
-11, -2, -1, 0, 11, 13, 18, 23, 34, 68, 77, 78, 88, 95, 234, 235, 323, 345, 434, 532, 745,
976,
];
for (position, value) in values.iter().enumerate() {
assert_eq!(Some(position), binary_search(*value, &values));
}
}
#[test]
fn test_string_uppercase() {
let &values = &[
"Alpaca", "Cat", "Dog", "Horse", "Leopard", "Mouse", "Rat", "Zebra",
];
assert_eq!(Some(2), binary_search("Dog", &values))
}
#[test]
fn test_string_lowercase() {
let &values = &[
"alpaca", "cat", "dog", "horse", "leopard", "mouse", "rat", "zebra",
];
assert_eq!(Some(7), binary_search("zebra", &values))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment