I want to write a binary search for a vector of tuples (start,end). (start,end) are pairs and they cover a single continuous range. I get error after error when trying to fix it. Can someone link a helpful resource or give an opinion how to best program this?
I check if the tuple at position mid+1 covers my offset, if yes I return this tuple if not I recurse with the side that has the offset in its intervals.
Is there something equivalent to "if a ? b : c" like in java or c++?
pub fn tuple_matches(tuple:&(usize,usize), offset:usize) -> bool {
if offset > tuple.0 && offset < tuple.1 {
return true;
} else {
false
}
}
pub fn binary_search_get_index(vector:&[(usize,usize)], offset:usize) -> &(usize,usize) {
let low = 0;
let high = vector.len();
let mid = high/2;
let tuple = vector.get(mid+1).unwrap();
if tuple_matches(tuple, offset) {
return tuple;
} else {
let tuple = vector.get(mid).unwrap();
let tuple2 = if tuple.0 > offset {
binary_search_get_index(&vector[0..mid], offset)}
} else {
binary_search_get_index(&vector[mid+1..high], offset)
};
tuple2
}
The standard library already has an implementation of binary search. To find the interval that contains a given number, you could do something like this:
use std::cmp::Ordering;
fn tuple_cmp(tuple: &(usize, usize), offset: usize) -> Ordering {
if offset < tuple.0 {
Ordering::Greater
} else if offset > tuple.1 {
Ordering::Less
} else {
Ordering::Equal
}
}
pub fn binary_search_get_index(vector:&[(usize,usize)], offset:usize) -> (usize,usize) {
match vector.binary_search_by(|tuple| tuple_cmp(tuple, offset)) {
Ok(idx) => vector[idx],
Err(_) => panic!("No tuple contains {offset}"),
}
}
fn main() {
let ranges = [(0, 2), (3, 7), (8, 10)];
for i in 0..=10 {
println!("{} {:?}", i, binary_search_get_index(&ranges, i));
}
}