php实现二分查找算法
时间:2021-07-01 10:21:17
帮助过:20人阅读
- // $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
- }
|
php