The dichotomy method is suitable when the amount of data is large, but the precondition of using dichotomy is that the data is not duplicated in order .
Binary search, also known as binary query, as the name implies is from the middle of the comparison to find, the basic idea is: the assumption of data in ascending order, for the given value X, from the middle of the sequence of the comparison, if the current position value equals X, the query succeeds, if X is less than the current position value, Look in the first half of the sequence, and if X is greater than the current position value, continue searching in the second half of the sequence until it is found.
Under the Java.util package has a arrays class, which provides a two-point method of query, you can go to see how the specific source code is implemented:
View the BinarySearch (int[] a,int key) method in Java.util.Arrays:
The source code is as follows:
1 // Use the binary search method to search for the specified array of int, which has obtained the subscript of the specified key value in the array 2 Public Static int binarysearch (intint key) {3 // Call internal method 4 return binarySearch0 (A, 0, a.length, key); 5 }
1 //JDK-provided binary search source code2 Private Static intBinarySearch0 (int[] A,intFromIndex,intToindex,intkey) {3 intlow = FromIndex;//Low Pointer4 intHigh = toIndex-1;//High Pointer5 //exits while loop when the value of the low pointer is greater than the value of the high pointer6 while(Low <=High ) {7 intMid = (low + high) >>> 1;//take the middle value8 intMidval =A[mid];9 Ten if(Midval <key) OneLow = mid + 1; A Else if(Midval >key) -High = Mid-1; - Else the returnMid//Key found - } - return-(low + 1);//key not found. -}
Basic Knowledge (03)--Two points inquiry