二分查找
/**
* 二分查找(有序序列)
*/
function binaryAlgorithm($list, $item)
{
$low = 0;
$high = count($list) - 1;
while ($low <= $high) {
$mid = floor($low + $high) / 2;
$guess = $list[$mid];
if ($guess == $item) {
return $mid;
} elseif ($guess > $item) {
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
return null;
}
var_dump(binaryAlgorithm([1, 4, 5, 7, 3, 8, 9], 8));

浙公网安备 33010602011771号