Home  >  Article  >  Backend Development  >  Binary search PHP implementation

Binary search PHP implementation

WBOY
WBOYOriginal
2016-07-25 08:46:12846browse
  1. /**Binary search: Find the position of a value in the array
  2. * @$arr: The array of operations, provided that it is arranged in order
  3. * @$val: The value to be searched for
  4. * @$low: The starting position of the search, the default is from the array Find the first number
  5. * @hight: The end position of the search
  6. **/
  7. function binarySearch($arr, $val, $hight, $low=0){
  8. while($low <= $hight){
  9. $ mid = ceil($low + ($hight - $low) / 2);
  10. if($arr[$mid] == $val){
  11. return $mid;
  12. }elseif($arr[$mid] > $val){
  13. $hight = $mid -1;
  14. }else{
  15. $low = $mid +1;
  16. }
  17. }
  18. return -1;
  19. }
  20. header('Content-Type: text/html; charset =utf-8');
  21. //Generate an array
  22. $arr = range(0,20);
  23. echo '
    ';</li>
    <li>print_r($arr);</li>
    <li>echo '
    ' ;
  24. $low = 0;
  25. $hight = count($arr) - 1;
  26. $findVal = rand(0, 20);
  27. $index = binarySearch($arr, $findVal, $hight, $low);
  28. printf("The value '%d' found is the subscript '%s' in the array", $findVal, $index);
  29. ?>
Copy code

PHP


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn