How to implement recursive binary search in Rust

1 Answer

0 votes
fn recursive_binary_search(arr: &[i32], left: usize, right: usize, to_find: i32) -> i32 {
    if right >= left {
        let mid = left + (right - left) / 2;

        if arr[mid] == to_find {
            return mid as i32;
        }

        if arr[mid] > to_find {
            return recursive_binary_search(arr, left, mid - 1, to_find);
        }

        return recursive_binary_search(arr, mid + 1, right, to_find);
    }

    -1
}

fn main() {
    let arr = [2, 3, 6, 7, 12, 13, 17, 19, 21, 30];
    let to_find = 13;

    let index = recursive_binary_search(&arr, 0, arr.len() - 1, to_find);

    if index == -1 {
        println!("not found");
    } else {
        println!("Found at index: {}", index);
    }
}


   
/*
run:
  
Found at index: 5
  
*/

 



answered Dec 13, 2024 by avibootz

Related questions

1 answer 82 views
1 answer 100 views
1 answer 127 views
1 answer 112 views
1 answer 112 views
1 answer 107 views
1 answer 125 views
...