php实现二分查找

时间:2022-11-05 10:06:31
<?php
class BinSch{
/*
* 二分查找,针对顺序表才有用
*/
public function search($arr,$k,$low,$high){
if($low<=$high){
$mid = floor(($low+$high)/2);
}
if ($arr[$mid] == $k){
return $mid;
} if($arr[$mid]>$k){
return $this->search($arr, $k, $low, $mid-1);
} if ($arr[$mid]<$k){
return $this->search($arr, $k, $mid+1, $high);
} return false;
}
} class Client{
public static function main(){
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$obj = new BinSch();
echo $obj->search($arr, 10, 0, 15);
}
} Client::main();
?>

  下面是非递归的二分查找

<?php
function serech($arr,$k){
sort($arr);
$low = 0;
$high = count($arr)-1;
while($low<=$high){
$mid = ($low+$high)/2;
if($arr[$mid]<$k){
$low = $mid+1;
}elseif ($arr[$mid]>$k){
$high = $mid-1;
}else {
return $arr[$mid];
}
}
return -1;
}
$arr = array(1,2,3,4,6,7,8,9);
$a = serech($arr,5);
var_dump($a);