二分法查找

仅限于正序数组

//二分查找
function bin_search($arr,$n){
  
    $start=0;
    $end=count($arr)-1;
  
    while($start<=$end){
        $mid=intval(($start+$end)/2);
  
        if($arr[$mid]==$n){
            return $mid;
        }else if($n > $arr[$mid]){
            $start=$mid+1;
        }else{
            $end=$mid-1;
        }
    }
}
  
$arr=array(3,4,5,7,9,10);
//$arr=array(23,14,10,7,5,3);
echo bin_search($arr,7);//查找7是第几个成员

标签: 二分查找