第一種寫法spa
public
static
int
binarySearch(Integer[] srcArray,
int
des) {
code
//定義初始最小、最大索引
索引
int
low =
0
;
static
int
high = srcArray.length -
1
;
while
//確保不會出現重複查找,越界
co
while
(low <= high) {
return
//計算出中間索引值
search
int
middle = (high + low)>>>
1
;
//防止溢出
arc
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; } } } }