In this paper, we introduce the binary search (binary lookup) algorithm of PHP ordered table lookup, briefly introduce the concept and principle of two-point lookup method, and analyze the relevant operation skills of PHP based on binary search algorithm for sequential linear table search, and the need for friends can refer to it, hoping to help everyone.
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
Two fork 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.