Created
September 21, 2019 10:23
-
-
Save rust-play/2b326756b046847ba5c66e33bec1aedf to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
use std::convert::TryInto; | |
fn binary_search<'a>(ar:&'a [i32], elem:i32, startIndex:usize, endIndex:usize) -> isize{ | |
let mid:usize = (startIndex + endIndex)/2; | |
let mut res:isize = -1; | |
let midelem:i32 = ar[mid]; | |
if startIndex > endIndex {//|| (startIndex == endIndex && midelem != elem) { | |
return res; | |
} | |
println!("start = {}, end ={}, and mid = {},",startIndex, endIndex, mid); | |
if midelem == elem{ | |
res = mid.try_into().unwrap(); | |
}else if midelem > elem { | |
res = binary_search(ar, elem, startIndex, mid - 1); | |
}else{ | |
res = binary_search(ar, elem, mid + 1, endIndex); | |
} | |
return res; | |
} | |
fn main() { | |
let a:[i32;5] = [1,2,3,4,5]; | |
println!("Index of 0 = {}", binary_search(&a, 90, 0, a.len()-1)); | |
println!("The result is {}", (8/3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment