This article describes the PHP binary lookup algorithm. Share to everyone for your reference, specific as follows:
BinarySearch
The method used in the binary lookup is relatively easy to understand, taking an array as an example:
① first takes the value in the middle of the array floor (LOW+TOP)/2),
② then, by comparing the number you want to find, if it is larger than the middle value, replace the first value with the next position in the middle position, and continue with the first step, if you are smaller than the median, replace the tail value with the middle position, and continue with the first step.
③ repeat the second step until you find the target number.
Like looking 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 value 9, is smaller than 23, then the first position is updated to 2+1 that is 3; then the middle position is (3+4)/2=3, the value is 23, the comparison is equal to find
non-recursive algorithm:
// $target is the target to find $arr is already sorted array
function binary (& $arr, $low, $top, $target) {
while ($low <= $top) {
//Because the PHP pickup is decimal, it is rounded down, but it is also not added, and the array will 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
}
}
More about PHP Interested readers can view the site topics: "PHP Search Techniques and Methods Summary", "PHP Data structure and algorithm tutorial", "PHP Programming Algorithm Summary", "PHP encryption Method Summary", "PHP coding and transcoding Operation skills Summary", " Introduction to PHP object-oriented programming program, "PHP Mathematical Calculation Skills Summary", "PHP array Operation techniques Encyclopedia", "PHP string (String) Usage summary", "PHP Regular Expression Usage Summary", and "PHP Common database Operation Skills Summary"
I hope this article will help you with the PHP program design.