Binary find two implementations

Source: Internet
Author: User

  Public classBisearch {/**     * @paramargs*/     /*Binary Lookup-When the lookup table is an ordered table, you can use binary to find; Basic idea: In the ordered table, take the intermediate element as the comparison object, if the given value K is equal to the middle record keyword, the search succeeds; if the given value K is less than the middle record keyword, the left half of the table continues to be searched, and if the given value K is greater than the middle record keyword, the right half of the table    Until the lookup succeeds/fails. */      //Binary Lookup non-recursive algorithm//The query successfully returns the subscript ordinal of the object, and returns-1 on failure.     intBisearch (intR[],intNintk) {intLow=0; intHigh=n-1;  while(low<=High ) {             intMid= (Low+high)/2; if(r[mid]==k)returnmid; Else                 if(r[mid]<k) Low=mid+1; Else High=mid-1; }         return-1; }       //binary lookup recursive algorithm//The query successfully returns the subscript ordinal of the object, and returns-1 on failure.     intBISEARCH2 (intR[],intLowintHighintk) {if(low>High )return-1; Else         {             intMid= (Low+high)/2; if(r[mid]==k)returnmid; Else                 if(r[mid]<k)returnBISEARCH2 (r,mid+1, high,k); Else                     returnBISEARCH2 (r,low,mid-1, K); }     }           Public Static voidMain (string[] args) {bisearch bs=NewBisearch (); intr[]={1,2,3,4,5}; SYSTEM.OUT.PRINTLN (BS. Bisearch (R,5,5)); SYSTEM.OUT.PRINTLN (BS. BISEARCH2 (R,1,5,5)); }  } 

Binary find two implementations

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.