用二分法判断数组中的值是否存在
function search($array,$k,$low=0,$high=0){
if(count($array)!=0 and $high==0){
$high = count($array);
}
if($low <= $high){
$mid = intval(($low+$high)/2);
if($array[$mid] == $k){
return $mid;
}elseif($k < $array[$mid]){
return search($array,$k,$low,$mid-1);
}else{
return search($array,$k,$mid+1,$high);
}
}
return "没有要查找的值";
}
$array = array(3,4,5,7,8,9,10);
echo search($array,4);
$arr = array(2,4,5,6,7,8,9,10);
$low = 0;
$search = 6;
$high = count($arr)-1;
while($low <= $high){
$mid = intval(($low+$high)/2);
if($arr[$mid]==$search){
echo "你要查找的值在数组内的下标为".$mid; break;
}elseif($arr[$mid] > $search){
$high = $mid -1;
}else{
$high = $mid+1;
}
}