This time for you to bring PHP binary search algorithm case, the use of PHP binary to find the attention of what, the following is the actual case, together to see.
Brief introduction:
Binary search technology, also known as binary lookup. The premise is that the records in the linear table must be orderly (usually from small to orderly), and the linear table must be stored sequentially.
Basic idea:
In an ordered table, the intermediate record is used as the comparison object, if the given value is equal to the key of the intermediate record, the search succeeds; If the given value is less than the middle record, the left half of the intermediate record continues to be searched, and if the given value is greater than the middle record, the right half of the middle record is searched. Repeat the process until the lookup succeeds, or if all lookup zones are not logged, the lookup fails.
Code:
<?php//binary search (binary lookup) algorithm (provided that the array must be an ordered array) The time complexity is O (logn) $i = 0; Number of storage comparisons//@param the array to be found//@param the number function Binsearch ($arr, $num) {$count = count ($arr) to be searched, $lower = 0; $high = $count-1; Global $i; while ($lower <= $high) { $i + +;//Counter if ($arr [$lower] = = $num) { return $lower; } if ($arr [$high] = = $num) { return $high; } $middle = Intval (($lower + $high)/2); if ($num < $arr [$middle]) { $high = $middle-1; } else if ($num > $arr [$middle]) { $lower = $middle + 1; } else{ return $middle;} }//Return-1 means find failed return-1;} $arr = Array (0,1,16,24,35,47,59,62,73,88,99), $pos = Binsearch ($arr,;p) rint ($pos); echo "<br>"; echo $i;
Operation Result:
73
Summarize:
The time complexity of binary lookups is O (Logn). However, because the precondition of binary lookup is that ordered table sequential storage (array) is required, if the ordered table needs frequent insert or delete operations, maintaining ordered sorting will bring a lot of work.
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP Long Connection use case study
PHP application container and deployment use of detailed