Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 21, 2019 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/2b326756b046847ba5c66e33bec1aedf to your computer and use it in GitHub Desktop.
Save rust-play/2b326756b046847ba5c66e33bec1aedf to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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