当前位置:Gxlcms > PHP教程 > php实现二分查找算法

php实现二分查找算法

时间:2021-07-01 10:21:17 帮助过:20人阅读

  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

人气教程排行