feat: Add binary search implementation and integrate it into main.rs

This commit is contained in:
TzuWei 2026-02-07 21:54:22 +09:00
parent 09c121833d
commit d706339351
Signed by: tzuwei-huang
GPG Key ID: 88A0D3DA7558EE01
3 changed files with 34 additions and 1 deletions

View File

@ -1,3 +1,19 @@
mod search;
use search::binary_search::binary_search;
fn main() {
println!("Hello, world!");
let array = [1, 3, 5, 7, 9, 11, 13, 15];
let target = 7;
match binary_search(&array, target) {
Some(index) => println!("Found {} at index {}", target, index),
None => println!("{} not found in the array", target),
}
let target = 6;
match binary_search(&array, target) {
Some(index) => println!("Found {} at index {}", target, index),
None => println!("{} not found in the array", target),
}
}

View File

@ -0,0 +1,16 @@
pub fn binary_search(array: &[i32], target: i32) -> Option<usize> {
let mut left = 0;
let mut right = array.len();
while left < right {
let mid = left + (right - left) / 2;
if array[mid] == target {
return Some(mid);
} else if array[mid] < target {
left = mid + 1;
} else {
right = mid;
}
}
None
}

1
src/search/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod binary_search;