时间:2021-07-01 10:21:17 帮助过:1人阅读
循环
function binary(&$arr,$low,$top,$target){ while($low <= $top){ $mid = floor(($low+$top)/2); echo $mid."<br>"; if($arr[$mid]==$target){ return $arr[$mid]; }elseif($arr[$mid]<$target){ $low = $mid+1; }else{ $top = $mid-1; } } return -1; }
递归
function binaryRecursive(&$arr,$low,$top,$target){ if($low<=$top){ $mid = floor(($low+$top)/2); if($mid==$target){ return $arr[$mid]; }elseif($arr[$mid]<$target){ return binaryRecursive($arr,$mid+1,$top,$target); }else{ return binaryRecursive($arr,$low,$top-1,$target); } }else{ return -1; } }
注意:二分查找的前提是数组有序排列
以上就是php 实现二分查找实例代码的详细内容,更多请关注Gxl网其它相关文章!