php dichotomy
伊谢尔伦
伊谢尔伦 2017-05-16 13:03:53
0
2
344

![Picture uploading...]

To find one of the 100 numbers, logically speaking, it should take at most 7 steps. Why is it only 15 steps?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
習慣沉默

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;

巴扎黑
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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template