Home >Backend Development >PHP Tutorial >PHP implements binary search algorithm

PHP implements binary search algorithm

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 08:43:03789browse
  1. // $low and $high have to be integers
  2. function BinarySearch( $array, $key, $low, $high )
  3. {
  4. if( $low > $high ) // termination case
  5. {
  6. return -1;
  7. }
  8. $middle = intval( ( $low+$high )/2 ); // gets the middle of the array
  9. if ( $array[$middle] == $key ) // if the middle is our key
  10. {
  11. return $middle;
  12. }
  13. elseif ( $key < $array[$middle] ) // our key might be in the left sub-array
  14. {
  15. return BinarySearch( $array, $key, $low, $middle-1 );
  16. }
  17. return BinarySearch( $array, $key, $middle+1, $high ); // our key might be in the right sub-array
  18. }
复制代码

php


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn