pub fn binary_search(array: &[i32], target: i32) -> Option<usize>
Expand description
Performs a binary search to find the index of a target value in a sorted array.
This function assumes that the array is sorted in ascending order. It works by repeatedly dividing the search interval in half. If the target is less than the middle element, the search continues in the left half, and if the target is greater, the search continues in the right half. This process continues until the target is found or the search interval is empty.
§Arguments
array
- A reference to a sorted slice of integers where the target value is searched.target
- The integer value to search for in the array.
§Returns
Some(usize)
- If the target is found, returns the index of the target in the array.None
- If the target is not found, returnsNone
.
§Examples
use dsa::algorithms::searching::binary_search;
let array = [1, 2, 3, 4, 5];
assert_eq!(binary_search(&array, 3), Some(2));
assert_eq!(binary_search(&array, 6), None);