PHP to implement a binary lookup program code

Source: Internet
Author: User

Dichotomy (Dichotomie) is the method of splitting in two. Set the closed range [A,b] to R. The successive binary method is to create the following interval sequence ([an,bn]): A0=a,b0=b, and for either natural number n,[an+1,bn+1] or equal to [AN,CN], or equal to [cn,bn], where the CN represents the midpoint of [an,bn].

Example 1


Header (' content-type:text/html; charset=utf-8; ');

$arr = Array (2,33,22,1,323,321,28,36,90,123);
Sort ($arr);

Two-Way Search
echo $index = BinarySearch ($arr, 321);

function BinarySearch ($arr, $key) {
$len = count ($arr);
$mid =-1;
$start = 0;
$end = $len-1;

while ($start <= $end) {
$mid = (int) (($start + $end)/2);
echo $mid. " \ n ";
if ($arr [$mid] = = $key) {
return $mid;
}else if ($arr [$mid] < $key) {
$start = $mid +1;
}else if ($arr [$mid] > $key) {
$end = $mid-1;
}
}
}


Example 2

<?php
The search function $array the array, $k the value to find, $low the minimum key value for the lookup range, $high the maximum key value for the lookup range
function Search ($array, $k, $low =0, $high =0)
{
if (count ($array)!=0 and $high = = 0)//To determine whether the first call
{
$high = count ($array);
}
if ($low <= $high)//If there are remaining array elements
{
$mid = Intval (($low + $high)/2); Take the middle value of $low and $high
if ($array [$mid] = = $k)//if found then return
{
return $mid;
}
ElseIf ($k < $array [$mid])//If not found, continue to find
{
Return Search ($array, $k, $low, $mid-1);
}
Else
{
Return Search ($array, $k, $mid +1, $high);
}
}
return-1;
}
$array = Array (4,5,7,8,9,10); Test search function
Echo Search ($array, 8); Call the search function and output the search results
?>

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.