feat: Add binary search implementation and integrate it into main.rs
This commit is contained in:
parent
09c121833d
commit
d706339351
18
src/main.rs
18
src/main.rs
@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
16
src/search/binary_search.rs
Normal file
16
src/search/binary_search.rs
Normal 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
1
src/search/mod.rs
Normal file
@ -0,0 +1 @@
|
||||
pub mod binary_search;
|
||||
Loading…
x
Reference in New Issue
Block a user