PHP 二分查找
答案
function binarySearch($array, $search)
{
$low = 0;
$high = count($array) - 1;
if ($search < $array[$low] || $search > $array[$high]) {
return false;
}
while ($low <= $high) {
$mid = floor(($high + $low) / 2);
if ($array[$mid] > $search) {
$high = $mid - 1;
} else if ($array[$mid] < $search) {
$low = $mid + 1;
} else {
return $mid;
}
}
return false;
}
时间复杂度:O(log n)