二分查找法
function binarySearch($arr, $val, $hight, $low = 0) {
$i = 0;
while ($low <= $hight) {
$i++;
$mid = ceil($low + ($hight - $low) / 2);
if ($arr[$mid] == $val) {
echo $i . PHP_EOL;
return $mid;
} elseif ($arr[$mid] > $val) {
$hight = $mid - 1;
} else {
$low = $mid + 1;
}
}
return - 1;
}
调用函数
$arr = range(20, 40);
$low = 0;
$hight = count($arr) - 1;
$findVal = rand(10, 50);
echo $findVal . PHP_EOL;
$result = binarySearch($arr, $findVal, $hight, $low);
标签:二分,arr,findVal,hight,查找,low
From: https://www.cnblogs.com/qjwlv/p/17215282.html