第一种写法
public
static
int
binarySearch(Integer[] srcArray,
int
des) {
//定义初始最小、最大索引
int
low =
0
;
int
high = srcArray.length -
1
;
//确保不会出现重复查找,越界
while
(low <= high) {
//计算出中间索引值
int
middle = (high + low)>>>
1
;
//防止溢出
if
(des == srcArray[middle]) {
return
middle;
//判断下限
}
else
if
(des < srcArray[middle]) {
high = middle -
1
;
//判断上限
}
else
{
low = middle +
1
;
}
}
//若没有,则返回-1
return
-
1
;
}
第二种写法:
public int find (long[] strs , long searchKey) {
int lowerBound = 0;
int upperBound = strs.length -1;
int curInt;
while (true) {
curInt = (upperBound - lowerBound)/2;
if (strs[curInt]==searchKey) {
return curInt;
} else if (lowerBound>upperBound){
return strs.length;
} else {
if (strs[curInt] < searchKey) {
lowerBound =curInt+1;
}else {
upperBound=curInt-1;
}
}
}
}