Long time no write algorithm. Just remember the recursive method. The results were tested under the stack.
The idea is to take the middle point of the range, to determine whether to find the value, is the output, not the two critical value of the range, and constantly update the critical value until it is found, the given set must be ordered.
Write your own code:
1 Packagecom.gh;2 3 Importjava.util.Arrays;4 /**5 * Binary search algorithm implementation6 * @authorGanhang7 *8 */9 Public classSearch {Ten Public Static voidMain (string[] args) { OneSearch1 (0, 10000, 20000); A if(Search2 (0,2100000001,200000100)){ -SYSTEM.OUT.PRINTLN ("Found!")); - } the ElseSystem.out.println ("Not Found!")); - } - /** - * Do not bother to send an array, directly from A to B to find n ... + * find it easier to achieve points than the two points of an array - * @parama + * @paramb A * @paramN at */ - //The idea is too native to pass the stack. - Public Static voidSearch1 (intAintBintN) { - intTMP = (int) (A + B)/2; - if(A = = TMP | | b = =tmp) { -System.out.println ("Not Found!") "); in return; - } to if(n = =tmp) { +SYSTEM.OUT.PRINTLN ("Found! "); -}Else if(N >tmp) the SEARCH1 (tmp, B, n); * Else if(N <tmp) $ Search1 (A, TMP, N);Panax Notoginseng } - //Recursive Implementation the Public Static BooleanSEARCH2 (intAintBintN) { + inttmp; A while(true){ theTmp= (int) (A+B)/2; + if(n==tmp)return true; - Else if(n>tmp) {a=tmp;} $ Else if(n<tmp) {b=tmp;} $ if(a==b)return false; - } - } the}
Compare the Arrays tool class with the two-point lookup, self-annotated the next
1 Private Static intBinarySearch0 (int[] A,intFromIndex,intToindex,2 intkey) {3 intLow =FromIndex;4 intHigh = ToIndex-1;//generally is a length-1,java in the general end of the seal is not sealed5 6 while(Low <=High ) {7 intMid = (low + high) >>> 1;//Unsigned Right shift one equivalent to 2, but fast.8 intMidval =A[mid];9 Ten if(Midval <key) OneLow = mid + 1;//Optimization A Else if(Midval >key) -High = Mid-1;//Optimization - Else the returnMid//Key found return subscript - } - return-(low + 1);//key not found. Return negative indicates not found, this tip 6 -}
The binary search algorithm of Java Learning