Last active
January 28, 2019 14:15
-
-
Save aristotle9/2440e31b11cc59412506e4dc016d81fa to your computer and use it in GitHub Desktop.
binary search in ordered list, if not found, return the nearest **left** [(left + right)/2] index.(if need **right** index, use mid = [(left + right + 1) / 2])
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const LIST: &[u32] = &[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]; | |
fn search(x: u32) -> usize { | |
let mut left: usize = 0; | |
let mut right: usize = LIST.len(); | |
println!("\n\nstart search x({}) in {:?}", x, LIST); | |
let mut step: u32 = 0; | |
while true { | |
let mid = (left + right) / 2; | |
let val = LIST[mid]; | |
println!("\nstep {}: ({} - {} - {}), val {}", step, left, mid, right, val); | |
if x > val { | |
if left == mid { | |
// nearest returned here | |
println!("left == mid, return;"); | |
return mid; | |
} | |
println!("x > val, left = mid ({})", mid); | |
left = mid; | |
} else if x < val { | |
// if the mid = (left + right + 1) / 2 | |
// test right == mid here | |
// return the nearest right bound | |
println!("x < val, right = mid({})", mid); | |
right = mid; | |
} else { | |
// exractly returned here | |
println!("x == val, return;"); | |
return mid; | |
} | |
step += 1; | |
} | |
return 0; | |
} | |
fn main() { | |
assert!(search(0) == 0); | |
assert!(search(10) == 1); | |
assert!(search(20) == 2); | |
assert!(search(30) == 3); | |
assert!(search(40) == 4); | |
assert!(search(50) == 5); | |
assert!(search(60) == 6); | |
assert!(search(70) == 7); | |
assert!(search(80) == 8); | |
assert!(search(90) == 9); | |
assert!(search(100) == 9); | |
assert!(search(1) == 0); | |
assert!(search(15) == 1); | |
assert!(search(25) == 2); | |
assert!(search(65) == 6); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment