Binary search runs in logarithmic time in the worst case, making O(log n) comparisons, where n is the number of elements in the array. Binary search is faster than linear search except for small arrays. However, the array must be sorted (https://gist.github.com/mikhail-krainik/cf92a17ce7a393b0779f3142a10910d5) first to be able to apply binary search.
Last active
February 1, 2023 21:38
-
-
Save mykhailokrainik/2ffe7316c6b66f8344c7ddf6b55c1fdb to your computer and use it in GitHub Desktop.
Implementation of the binary search algorithm (logarithmic search)
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(arr: &[i32], value: i32) -> Option<usize> { | |
let mut mid; | |
let mut low = 0; | |
let high = arr.len(); | |
while low <= high { | |
mid = low + (high - low) / 2; | |
match arr.get(mid) { | |
Some(arr_value) => match value.cmp(&arr_value) { | |
Ordering::Less => low = mid - 1, | |
Ordering::Greater => low = mid + 1, | |
Ordering::Equal => return Some(mid), | |
}, | |
None => return None, | |
} | |
} | |
return None; | |
} |
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
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn it_case_0_for_binary_search() { | |
let result = binary_search(&[], 10); | |
assert_eq!(result, None); | |
} | |
#[test] | |
fn it_case_1_for_binary_search() { | |
let result = binary_search(&[3], 3); | |
assert_eq!(result, Some(0)); | |
} | |
#[test] | |
fn it_case_2_for_binary_search() { | |
let result = binary_search(&[3, 5], 5); | |
assert_eq!(result, Some(1)); | |
} | |
#[test] | |
fn it_case_n_for_binary_search() { | |
let result = binary_search(&[2, 3, 4, 5, 10, 16, 20], 16); | |
assert_eq!(result, Some(5)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment