Two-part method PHP

Source: Internet
Author: User

To start learning some algorithms recently ... Some algorithms will make you sigh true to the clever. I think some algorithms have been invented and need to be a mathematician. Such as quick sort, simply sigh how he thought of ... No other people's intelligence can only read more than remember haha ~

Today write a simple algorithm, dichotomy.

<?PHPfunctionBsearch ($v,$arr){    $low= 0; $high=Count($arr)-1;//use subscript, note minus 1     while($low<=$high){//Note the equals sign        $i=intval(($high+$low)/2); if($arr[$i] >$v){            $high=$i-1; } Else if($arr[$i] <$v){            $low=$i+1; } Else {            return  $i; }    }    return-1;//returned when not found-1}$arr=Array(    1, 3, 5, 7, 9, 13);EchoBsearch (13,$arr);//5Echo' ;EchoBsearch (14,$arr);//-1

Seemingly simple algorithm, or self-write down good haha ~

Note that when using the while, be sure to guard against infinite loops, pay attention to the termination of the cycle of judgment. For example $low<= $high, this equals number must have.

Two-part method PHP

Related Article

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.