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
}