![Picture uploading...]
To find one of the 100 numbers, logically speaking, it should take at most 7 steps. Why is it only 15 steps?
習慣沉默2017-05-16 13:05:53
The first execution of $flag = 50 uses else logic, but $i++ and $low+1 are not assigned to $low. Therefore, keep looping else
Modify line 24 $low= $low+1;
巴扎黑2017-05-16 13:05:53
function binarySearch($array, $val) {
$count = count($array);
$low = 0;
$high = $count - 1;
while ($low <= $high) {
$mid = intval(($low + $high) / 2);
if ($array[$mid] == $val) {
return $mid;
}
if ($array[$mid] < $val) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return false;
}