二分查找
public function binary($arr,$low,$high,$number)
{
while($low <= $high) {
$mid = floor(($low+$high)/2);
if($arr[$mid] == $number) {
return $mid;
} elseif ($arr[$mid] < $number) {
$low = $mid+1;
} else {
$high = $mid-1;
}
}
return -1;
}
二分递归查找
public function binaryRecursive($arr,$low,$high,$number)
{
if($low <= $high) {
$mid = floor(($low+$high)/2);//中间值
if($arr[$mid]==$number) {
return $mid;
} elseif ($arr[$mid] < $number) {
return $this->binaryRecursive($arr,$mid+1,$high,$number);
} else{
return $this->binaryRecursive($arr,$low,$mid-1,$number);
}
} else {
return -1;
}
}