fork(1) download
  1. <?php
  2.  
  3. function justBinarySearch($x, $list) {
  4. sort($list);
  5. $left = 0;
  6. $right = count($list) - 1;
  7. while ($left <= $right) {
  8. $mid = (int)(($left + $right)/2);
  9. if ($list[$mid] == $x) {
  10. return true;
  11. } elseif ($list[$mid] > $x) {
  12. $right = $mid - 1;
  13. } elseif ($list[$mid] < $x) {
  14. $left = $mid + 1;
  15. }
  16. }
  17. return false;
  18. }
  19. function binary(array $array, $needle) {
  20. $right = count($array) - 1;
  21. $left = 0;
  22.  
  23. while($left <= $right) {
  24. $mid = ($left + $right) / 2;
  25. if ($array[$mid] == $needle) {
  26. return $needle;
  27. }
  28. if ($array[$mid] > $needle) {
  29. $right = $mid - 1;
  30. }
  31. if ($array[$mid] < $needle) {
  32. $left = $mid + 1;
  33. }
  34. }
  35. return 0;
  36. }
  37. echo justBinarySearch(4, [1,21,3,4,2,99]);
  38.  
  39.  
Success #stdin #stdout 0.02s 52472KB
stdin
Standard input is empty
stdout
1