PHP 二分查找

答案

  1. function binarySearch($array, $search)
  2. {
  3. $low = 0;
  4. $high = count($array) - 1;
  5. if ($search < $array[$low] || $search > $array[$high]) {
  6. return false;
  7. }
  8. while ($low <= $high) {
  9. $mid = floor(($high + $low) / 2);
  10. if ($array[$mid] > $search) {
  11. $high = $mid - 1;
  12. } else if ($array[$mid] < $search) {
  13. $low = $mid + 1;
  14. } else {
  15. return $mid;
  16. }
  17. }
  18. return false;
  19. }

时间复杂度:O(log n)