algorithm_helper.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 16/6/24
  6. * Time: 上午1:18
  7. */
  8. class algorithm_helper
  9. {
  10. // static public function bsearch($needle, $haystack)
  11. // {
  12. // $high = count($haystack);
  13. // $low = 0;
  14. //
  15. // while ($high - $low >= 1){
  16. // $probe = ($high + $low) / 2;
  17. // if ($haystack[$probe] < $needle){
  18. // $low = $probe;
  19. // }else{
  20. // $high = $probe;
  21. // }
  22. // }
  23. //
  24. // if ($high == count($haystack) || $haystack[$high] != $needle) {
  25. // return false;
  26. // }else {
  27. // return $high;
  28. // }
  29. // }
  30. static function bsearch($x, $list)
  31. {
  32. $left = 0;
  33. $right = count($list)-1;
  34. while ($left <= $right) {
  35. $mid = ($left + $right) >> 1;
  36. if ($list[$mid] == $x) {
  37. return $mid;
  38. } elseif ($list[$mid] > $x) {
  39. $right = $mid - 1;
  40. } elseif ($list[$mid] < $x) {
  41. $left = $mid + 1;
  42. }
  43. }
  44. return -1;
  45. }
  46. }