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);
}
}
二分搜索
最新推荐文章于 2025-10-14 08:00:00 发布
本文介绍了一种在有序数组中进行高效搜索的二分查找算法,并通过Java代码实现了该算法。文章展示了如何定义查找范围并逐步缩小搜索区间直到找到目标元素或确定目标不存在于数组中。
2303

被折叠的 条评论
为什么被折叠?



