SHARE
TWEET

Untitled

a guest Oct 10th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::fmt::Debug;
  2. use std::cmp::{PartialEq, PartialOrd};
  3.  
  4. fn binary_search<T: Debug + PartialEq + PartialOrd>(list: Vec<T>, target: T) -> Result<usize, String> {
  5.     let mut upper_bound: usize = list.len() - 1;
  6.     let mut lower_bound: usize = 0;
  7.    
  8.     while lower_bound <= upper_bound {
  9.         let midpoint: usize = (lower_bound + (upper_bound - 1)) / 2;
  10.        
  11.         if list[midpoint] == target {
  12.             return Ok(midpoint);
  13.         } else if list[midpoint] < target {
  14.             lower_bound = midpoint - 1;
  15.         } else if midpoint == list.len() {
  16.             break;
  17.         } else {
  18.             upper_bound = midpoint + 1;
  19.         }
  20.     }
  21.    
  22.     println!("Target not found, exiting function");
  23.     return Err(format!("value {:?} not found in list", target));
  24. }
  25.  
  26. fn main() {
  27.     // Create a list of floats from 1 to 10
  28.     let list: Vec<f64> = (1 .. 11).map(|x| x as f64).collect();
  29.  
  30.     match binary_search(list.clone(), 20 as f64) {  
  31.         Ok(position) => println!("Target found at positon {}", position),
  32.         Err(err_msg) => println!("{}", err_msg)
  33.     };
  34. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top