public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arrays = new String[]{"a","b","c","d","e","fff","g","h","i","j",};
int positon = Arrays.binarySearch(arrays, "fff");
System.out.println("position is:"+positon);
}
测试结果:
position is:5
public static int binarySearch(char[] array, int startIndex, int endIndex, char value) {
checkBinarySearchBounds(startIndex, endIndex, array.length);
int lo = startIndex;
int hi = endIndex - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;//无符号右移
char midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}