两分法查找的前提:顺序方式存储,而且必须是排好序
直接上代码:
function search($array, $target, $low = 0, $high = 0){ $len = count($array);
$low = max($low, 0);
$high = $high == 0 ? $len : min($high, $len); while($low <= $high){ $m = $low + ceil((($high - $low) / 2));
$mv = $array[$m]; if($mv > $target){
$high = $m - 1;
}else if($mv < $target){
$low = $m + 1;
}else{
return $m;
}
} return -1;
} $array = array(1, 2, 4, 5, 7, 8, 9, 10);
echo search($array, 9);