public class BinarySearch {
public static int find(int searchKey, int[] orderArray) {
int lowBound = 0;
int highBound = orderArray.length - 1;
int curIn;
while (true) {
curIn = (lowBound + highBound) / 2;
if (orderArray[curIn] == searchKey)
return curIn;
else if (lowBound > highBound)
return orderArray.length;// 查找失败
else {// 如果还有查找空间
if (orderArray[curIn] > searchKey)
highBound = curIn - 1;
else if (orderArray[curIn] < searchKey)
lowBound = curIn + 1;
}
}
}
public static void main(String[] args) {
int[] arry = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int key = find(100, arry);
System.out.println(key);
}
}
二分搜索
最新推荐文章于 2022-11-04 12:32:19 发布