PHP-2분 찾기

4821 단어 이분 찾기
function binarySearch($arr,$findval,$leftIndex,$rigthIndex){

    if($leftIndex > $rigthIndex){

       echo ' ';

       return ;

    }

    $middleIndex = round(($leftIndex+$rigthIndex)/2);

    if($findval > $arr[$middleIndex]){

        binarySearch($arr, $findval, $middleIndex+1, $rigthIndex);

    }else if($findval < $arr[$middleIndex]){

        binarySearch($arr, $findval, $leftIndex, $middleIndex-1);

    }else{

        echo ' '. $middleIndex;

    }

}



 
#while 
function
binarySearch_(Array $arr, $target) { $low = 0; $high = count($arr) - 1; while($low <= $high) { $mid = floor(($low + $high) / 2); # if($arr[$mid] == $target){ return $mid; } # , if($arr[$mid] > $target){ $high = $mid - 1; } # , if($arr[$mid] < $target){ $low = $mid + 1; } } # return 'not found'; }

좋은 웹페이지 즐겨찾기