Skip to content

Commit bf21763

Browse files
committed
binary-search-in-rust
1 parent de7dbf1 commit bf21763

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Rust/binary-search.rs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
2+
let mut low = 0;
3+
let mut high = arr.len() as i32 - 1;
4+
5+
while low <= high {
6+
let mid = low + (high - low) / 2;
7+
let mid_value = arr[mid as usize];
8+
9+
if mid_value == target {
10+
return Some(mid as usize);
11+
} else if mid_value < target {
12+
low = mid + 1;
13+
} else {
14+
high = mid - 1;
15+
}
16+
}
17+
None
18+
}
19+
20+
fn main() {
21+
let sorted_array = [1, 3, 5, 7, 9, 11, 13, 15];
22+
let target = 7;
23+
24+
match binary_search(&sorted_array, target) {
25+
Some(index) => println!("Found target {} at index {}.", target, index),
26+
None => println!("Target {} not found in array.", target),
27+
}
28+
}

0 commit comments

Comments
 (0)