二分查找,返回数组的下标:
递归
~~~
<?php
$arr = [1,2,3,4,5,6,7,8,9];
$val =5;
function bin_recur_search($arr,$val){
global $time;
if(count($arr) >= 1){
$mid = floor(count($arr) / 2);
$time++;
if($arr[$mid] == $val){
return $arr[$mid];
}elseif($arr[$mid] > $val){
$arr = array_splice($arr,0,$mid);
return bin_recur_search($arr, $val);
}else{
$arr = array_slice($arr,$mid + 1);
return bin_recur_search($arr, $val);
}
}
return '未找到'.$val;
}
echo bin_recur_search($arr,$val);
?>
~~~
非递归
~~~
<?php
$arr = [1,2,3,4,5,6,7,8,9];
$val =5;
function zb($arr,$val){
$left=0;
$right=count($arr);
while($left<=$right){
$mid=floor(($left+$right)/2);
if($arr[$mid]==$val){
return $mid;
}elseif($arr[$mid]>$val){
$right = $mid-1;
}else{
$left=$mid+1;
}
}
return -1;
}
echo zb($arr,$val);
?>
~~~