1. The source code can be seen,BinarySearch method calls the BinarySearch0 method, BinarySearch0 method is the standard binary search implementation.
2. For the BinarySearch0 method, pay attention to the last return statement return-(low + 1); // key not found., that is, when you do not find the key to find, the return is a negative insertion point value, the so-called insertion point value is the first element larger than key in the array index, and this index is starting from 1.
For example: There is anarray {4,6,10,21,25,95); Return 2 2); Returns-1 4 of the index is1 20); Returns-4 21 of the index is4 30); Returns-6 95 of the index is6 100); Returns 7 100 is not in the array, is larger than all elements, the insertion point value is b.length+1 7
Why use-(low+1), because if with-low words, find 2 and find 4 results are 0, so it is wrong.
3. call the BinarySearch method before calling the Arrays.sort method to sort the array, otherwise the resulting return value is variable.
Public Static intBinarySearch (object[] A, Object key) {returnBinarySearch0 (A, 0, A.length, key); } //Like public version, but without range checks. Private Static intBinarySearch0 (object[] A,intFromIndex,intToindex, Object key) { intLow =FromIndex; intHigh = ToIndex-1; while(Low <=High ) { intMid = (low + high) >>> 1; @SuppressWarnings ("Rawtypes") Comparable Midval=(comparable) a[mid]; @SuppressWarnings ("Unchecked") intCMP =Midval.compareto (key); if(CMP < 0) Low= Mid + 1; Else if(CMP > 0) High= Mid-1; Else returnMid//Key found } return-(low + 1);//key not found.}
Java Foundation (Arrays.binarysearch) method