/*二分查找法
检索参数: 11*/
$arr =[1,2,3,4,5,6,7,8,9,10,11];
echo $index = bin_search($arr,11); // 10
// 迭代法
function bin_search($arr,$target){
$start=0 ; $end = count($arr)-1; $index = -1;
// 每次循环内比较中位数, 正确时返回当前索引, 错误时缩小范围, 直到范围判定为非法说明检索结束, 返回-1
while($start<=$end){
$middle = floor(($start+$end)/2);
if($target<$arr[$middle])$end = $middle-1;
else if($target>$arr[$middle]){
$start = $middle+1;
}
else {
return $middle;
}
}
return -1;
}
网友评论