Advertisement
Guest User

Binary Search

a guest
Jul 18th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.59 KB | None | 0 0
  1. <?php
  2.  
  3. function find($array, $x) {
  4.     $mid = floor(count($array)/2);
  5.     if ($array[$mid] === $x) { // integer found
  6.         return true;
  7.     } elseif (count($array) === 1) { // integer not found when only one element left
  8.         return false;
  9.     } elseif ($array[$mid] > $x) { // recursive function with lower array
  10.         return find(array_slice($array, 0, count($array)/2), $x);
  11.     } else  { // recursive function with upper array
  12.         return find(array_slice($array, count($array)/2), $x);
  13.     }
  14. }
  15.  
  16. // driver code
  17. $found = find(array(1,2,3,4,5,6),2);
  18. if ($found) {
  19.     echo 'Found';
  20. } else {
  21.     echo 'Not Found';
  22. }
  23.  
  24. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement