This article describes the PHP binary search algorithm. Share it for your reference, as follows:
binarySearch
The method used for binary search is easier to understand, taking arrays as an example:
① First take the value floor((low+top)/2) in the middle of the array,
② Then compare with the number you want to find. If it is larger than the intermediate value, replace the first value with the next position in the middle position and continue the first step of operation. If it is smaller than the intermediate value, replace the tail value with the previous position in the middle position and continue the first step of operation.
③ Repeat the second step until the target number is found
For example, look up the number 23 from 1, 3, 9, 23, 54,
The first position is 0, the tail position is 4, the middle position is 2. The value is 9, which is smaller than 23, and the first position is updated to 2+1, that is, 3; then the middle position is (3+4)/2=3, the value is 23, and the same is found
// Non-recursive algorithm:// $target is the target to be found $arr is an array already sortedfunction binary(&$arr,$low,$top,$target){ while($low <= $top){ // Since PHP has decimal numbers, it is rounded downward, but it can also be added, and the array will also be rounded. $mid = floor(($low+$top)/2); echo $mid."<br>"; if($arr[$mid]==$target){ return $arr[$mid]; }elseif($arr[$mid]<$target){ $low = $mid+1; }else{ $top = $mid-1; } } return -1; }
// Recursive algorithm:function binaryRecursive(&$arr,$low,$top,$target){ if($low<=$top){ $mid = floor(($low+$top)/2); if($mid==$target){ return $arr[$mid]; }elseif($arr[$mid]<$target){ return binaryRecursive($arr,$mid+1,$top,$target); }else{ return binaryRecursive($arr,$low,$top-1,$target); } }else{ return -1; } }
For more information about PHP related content, please check out the topic of this site:Summary of php search techniques and methods》、《PHP data structure and algorithm tutorial》、《Summary of PHP Programming Algorithm》、《Summary of php encryption method》、《Summary of PHP encoding and transcoding operation techniques》、《PHP object-oriented programming tutorial》、《Summary of PHP mathematical operation skills》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《Summary of usage of php regular expressions",and"Summary of common database operation techniques for php》
I hope this article will be helpful to everyone's PHP programming.