Binary Search to achieve promised logarithmic running time for sample (instead of linear!)

(cherry picked from commit ffcf289f713d5d92a74038ffa2fb6059d9995175)
This commit is contained in:
Tim Taubner 2022-06-23 16:51:47 +02:00
parent ace0f4ec50
commit 5a7e74d79c

View File

@ -318,37 +318,20 @@ pub struct KeyMut<'a, T, V> {
} }
// Find the lower control point corresponding to a given time. // Find the lower control point corresponding to a given time.
// It has the property to have a timestamp smaller or equal to t
fn search_lower_cp<T, V>(cps: &[Key<T, V>], t: T) -> Option<usize> fn search_lower_cp<T, V>(cps: &[Key<T, V>], t: T) -> Option<usize>
where where
T: PartialOrd, T: PartialOrd,
{ {
let mut i = 0;
let len = cps.len(); let len = cps.len();
if len < 2 { if len < 2 {
return None; return None;
} }
match cps.binary_search_by(|key| key.t.partial_cmp(&t).unwrap()) {
loop { Err(i) if i >= len => None,
let cp = &cps[i]; Err(i) if i == 0 => None,
let cp1 = &cps[i + 1]; Err(i) => Some(i-1),
Ok(i) if i == len - 1 => None,
if t >= cp1.t { Ok(i) => Some(i),
if i >= len - 2 {
return None;
}
i += 1;
} else if t < cp.t {
if i == 0 {
return None;
}
i -= 1;
} else {
break; // found
} }
} }
Some(i)
}