insgo
2020-07-10 11:31
采纳率: 50%
浏览 99
已采纳

php 2分查找, return true结果var_dump()是null

function searchNum($arr,$num,$start=0,$end=null){
    if($start>$end){
        return false;
    }
    $count=count($arr);
    if(!$end){
        $end=$count-1;
    }
    $mid=floor(($start+$end)/2);
    echo $num,'<br>';
    echo $mid,' : ',$arr[$mid],' ';
    if($arr[$mid]==$num){
         echo true;
        return true;
    }
    elseif($arr[$mid]>$num){
        searchNum($arr,$num,$start,$mid-1);
    }
    else{
        searchNum($arr,$num,$mid+1,$end);
    }
}
$arr1=[1,2,3,15,18,21,23,34,38,42,45,48,68,77,79,81,84,88,91,99,102,105,110];
var_dump(searchNum($arr1,45));
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • Tournesol1530215484 2020-07-13 16:15
    已采纳
    <?php 
    
    
    function searchNum($arr,$num,$start=0,$end=null){
        if($start>$end){
            return false;
        }
        $count=count($arr);
        if(!$end){
            $end=$count-1;
        }
        $mid=floor(($start+$end)/2);
    
        if($arr[$mid]==$num){
    
           return true;
    
        }
        elseif($arr[$mid]>$num){
            return searchNum($arr,$num,$start,$mid-1);
        }
        else{
           return searchNum($arr,$num,$mid+1,$end);
        }
    }
    
    
    $arr1=[1,2,3,15,18,21,23,34,38,42,45,48,68,77,79,81,84,88,91,99,102,105,110];
    
        $res=searchNum($arr1,45);
        var_dump($res);
    
    
    你的在 
    
    searchNum($arr,$num,$mid+1,$end);
    

    这里加return 不然

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题