//二分查找
$arr = array(0,1,2,3,4,5,6,7,8,9);
function bin_sch($array, $low, $high, $k){
if ($low <= $high){
$mid = intval(($low+$high)/2);
if ($array[$mid] == $k){
return $mid;
}elseif ($k < $array[$mid]){
return bin_sch($array, $low, $mid-1, $k);
}else{
return bin_sch($array, $mid+1, $high, $k);
}
}
return -1;
}
$key = bin_sch($arr , 0 , count($arr) , 4);
echo $key;
用php描述二分查找法
时间: 2024-10-07 05:24:20