当前位置 : 主页 > 网络编程 > PHP >

php实现二分查找算法

来源:互联网 收集:自由互联 发布时间:2021-07-03
// $low and $high have to be integers function BinarySearch( $array, $key, $low, $high ){ if( $low $high ) // termination case { return -1; } $middle = intval( ( $low+$high )/2 ); // gets the middle of the array if ( $array[$middle] == $key
// $low and $high have to be integers
 
function BinarySearch( $array, $key, $low, $high )
{
    if( $low > $high ) // termination case
    {
        return -1;
    }
 
    $middle = intval( ( $low+$high )/2 ); // gets the middle of the array
 
    if ( $array[$middle] == $key ) // if the middle is our key
    {
        return $middle;
    }
    elseif ( $key < $array[$middle] ) // our key might be in the left sub-array
    {
        return BinarySearch( $array, $key, $low, $middle-1 );
    }  
 
    return BinarySearch( $array, $key, $middle+1, $high ); // our key might be in the right sub-array
}
网友评论