quocvuongdn

Binary search in PHP example

Mar 10th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.52 KB | None | 0 0
  1. <?php
  2. function bin_search($arr, $searchKey) {
  3.     $left = 0;
  4.     $right = count($arr);
  5.    
  6.     while($left < $right) {
  7.         $middle = ($right + $left) / 2;
  8.         if ($arr[$middle] == $searchKey) {
  9.             $res = $middle;
  10.             break;
  11.         } elseif ($arr[$middle] > $searchKey) {
  12.             $right = $middle;
  13.         } else {
  14.             $left = $middle + 1;
  15.         }  
  16.     }
  17.     return $res;
  18. }
  19. $exArr = array(1, 1, 2, 2, 3, 9, 11, 16);
  20. $result = bin_search($exArr, 3);
  21. print $result.PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment