Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt::Debug;
- use std::cmp::{PartialEq, PartialOrd};
- fn binary_search<T: Debug + PartialEq + PartialOrd>(list: Vec<T>, target: T) -> Result<usize, String> {
- let mut upper_bound: usize = list.len() - 1;
- let mut lower_bound: usize = 0;
- while lower_bound <= upper_bound {
- let midpoint: usize = (lower_bound + (upper_bound - 1)) / 2;
- if list[midpoint] == target {
- return Ok(midpoint);
- } else if list[midpoint] < target {
- lower_bound = midpoint - 1;
- } else if midpoint == list.len() {
- break;
- } else {
- upper_bound = midpoint + 1;
- }
- }
- println!("Target not found, exiting function");
- return Err(format!("value {:?} not found in list", target));
- }
- fn main() {
- // Create a list of floats from 1 to 10
- let list: Vec<f64> = (1 .. 11).map(|x| x as f64).collect();
- match binary_search(list.clone(), 20 as f64) {
- Ok(position) => println!("Target found at positon {}", position),
- Err(err_msg) => println!("{}", err_msg)
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement