PHP Binary Lookup Example
In order to find the median value, the interpolation method can be used instead of the median method.
When the data in the ordered array is increased uniformly, the interpolation method can be used to reduce the LGN of the algorithm complexity from the value method to the LGLGN
Copy Code code as follows:
/**
* Second-search recursive solution
* @param type $subject
* @param type $start
* @param type $end
* @param type $key
* @return Boolean
*/
function Binarysearch_r ($subject, $start, $end, $key)
{
if ($start >= $end) return FALSE;
$mid = Getmidkey ($subject, $start, $end, $key);
if ($subject [$mid] = = $key) return $mid;
if ($key > $subject [$mid]) {
return binarysearch ($subject, $mid, $end, $key);
&NBSP}
if ($key <= $subject [$mid]) {
return binarysearch ($subject, $start, $mid, $key);
}
}
/**
* non-recursive algorithm for binary lookup
* @param type $subject
* @param type $n
* @param type $key
& nbsp;*/
Function Binarysearch_nr ($subject, $n, $key)
{
$low = 0;
$high = $n;
while ($low <= $high) {
$mid = Getmidkey ($subject, $low, $high, $key);
if ($subject [$mid] = = $key) return $mid;
if ($subject [$mid] < $key) {
$low = $mid + 1;
&NBSP;&NBSP}
if ($subject [$mid] > $key) {
$high = $mid-1;
&NBSP;&NBSP}
}
Function Getmidkey ($subject, $low, $high, $key)
{
/**
* Median algorithm 1 to take the median value not ($low + $high)/2 is due to prevent low and high when the overflow ....
*/
//return round ($low + ($high-$low)/2);
/**
* Improved interpolation algorithm for median, when the numerical distribution is uniform, then reduce the complexity of the algorithm to LGLGN
* Median algorithm 2
*/
Return round (($key-$subject [$low])/($subject [$high]-$subject [$low]) ($high-$low)));
}