- // $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
- }
复制代码
|