PHP 二分查找算法实现:在指定区间内查找数字
= $low) {
$mid = floor(($low + $high) / 2);
if ($arr[$mid] == $x)
return $mid;
if ($arr[$mid] > $x)
return binarySearch($arr, $low, $mid - 1, $x);
return binarySearch($arr, $mid + 1, $high, $x);
}
return -1;
}
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = binarySearch($arr, 0, $n - 1, $x);
if ($result == -1)
echo 'Element is not present in array';
else
echo 'Element is present at index ', $result;
?>
原文地址: https://www.cveoy.top/t/topic/lAAw 著作权归作者所有。请勿转载和采集!