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