fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut low = 0;
let mut high = arr.len() - 1;
while low <= high {
let mid = low + (high - low) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] < target {
low = mid + 1;
} else {
if mid == 0 { break; }
high = mid - 1;
}
}
None
}
fn main() {
let sorted_arr = [2, 4, 6, 8, 10, 12];
match binary_search(&sorted_arr, 8) {
Some(index) => println!("Found at index {}", index),
None => println!("Not found"),
}
}The binary search finds the target 8 at index 3 in the sorted array [2,4,6,8,10,12]. The code correctly calculates mid and adjusts low and high pointers.
Binary search relies on the sorted order to eliminate half of the search space each time by comparing the target with the middle element.
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut low = 0;
let mut high = arr.len() - 1;
while low <= high {
let mid = low + (high - low) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] < target {
low = mid + 1;
} else {
if mid == 0 { break; }
high = mid - 1;
}
}
None
}
fn main() {
let unsorted_arr = [10, 2, 8, 6, 4];
match binary_search(&unsorted_arr, 5) {
Some(index) => println!("Found at index {}", index),
None => println!("Not found"),
}
}Binary search on an unsorted array does not guarantee finding the target. Here, 5 is not in the array, so it returns None and prints "Not found".
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut low = 0;
let mut high = arr.len() - 1;
while low <= high {
let mid = low + (high - low) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] < target {
low = mid + 1;
} else {
if mid == 0 { break; }
high = mid - 1;
}
}
None
}
fn main() {
let empty_arr: [i32; 0] = [];
match binary_search(&empty_arr, 1) {
Some(index) => println!("Found at index {}", index),
None => println!("Not found"),
}
}When the array is empty, arr.len() is 0, so arr.len() - 1 underflows to a very large number, causing out-of-bounds access and panic.
Binary search requires at most log2(n) + 1 comparisons. For 64 elements, log2(64) = 6, so maximum comparisons are 7.
