Binary search algorithm

Source: Internet
Author: User

The premise of binary search algorithm:

1, for the index array;

2, for arrays that are already lined up.

Code Demo:

//function function: Find data from position $begin start to position $end in array $arr $sfunctionBinary_search ($arr,$s,$begin,$end){    $mid= Floor(($begin+$end)/2);//Locate the middle position    $mid _value=$arr[$mid];//gets the value of the middle item    if($mid _value==$s)    {        return true; }Else if($mid _value>$s)    {        if($begin>$mid-1)//if the starting position is larger than the end position, it means that it must not be found.        {            return false; }        //the middle item is bigger than the $s to find, go to the left to find it:        $re= Binary_search ($arr,$s,$begin,$mid-1); }Else    {        if($mid+1 >$end)//if the starting position is larger than the end position, it means that it must not be found.        {            return false; }        //the middle item is smaller than the $s to be searched, go to the right to find it;        $re= Binary_search ($arr,$s,$mid+1,$end); }    return $re;}

test code:

 <? php   $a  = array  ( 1,3,11,18,19,22,25,33,34,38,44,55,56,58  $search  = 35; //  The number to find   $len  = count  (  $a ); //  number, natural, maximum subscript is len-1//use the Binary_search () function to find len-1  $search  $v 1  = Binary_search ( $a ,  $search , 0, $len  -1 echo  "The result is:"  var_dump  ( $v 1 ); 

Test results:

· The result is: BOOL (false)

A little explanation of the efficiency (performance) problem of the binary lookup algorithm:

1000 data, about 10 times to find out;

100 complete data, about 20 times to find out;

1 billion data, about 30 times to find out;

4 billion data, about 32 times to find out.

Binary search algorithm

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.