PHP Two-point lookup two implementations example _php instance

Source: Internet
Author: User

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)));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.