php 二分查找
程序员文章站
2022-05-06 10:41:35
...
二分查找需要数组有序,效率为O(logn)
#二分查找functionbinarySearch(Array $arr, $target) {$low = 0;
$high = count($arr) - 1;
while($low $high) {
$mid = floor(($low + $high) / 2);
#找到元素if($arr[$mid] == $target) return$mid;
#中元素比目标大,查找左部if($arr[$mid] > $target) $high = $mid - 1;
#重元素比目标小,查找右部if($arr[$mid] $target) $low = $mid + 1;
}
#查找失败returnfalse;
}
$arr = array(1, 3, 5, 7, 9, 11);
$inx = binarySearch($arr, 1);
var_dump($inx);
?>