【发布时间】:2013-03-02 05:17:42
【问题描述】:
我有这个代码进行二分搜索。
public class BinarySearch {
private static int location;
private static int a = 14;
static int[] numbers = new int[]{3, 6, 7, 11, 14, 16, 20, 45, 68, 79};
public static int B_Search(int[] sortedArray, int key) {
int lowB = 0;
int upB = sortedArray.length;
int mid;
while (lowB < upB) {
mid = (lowB + upB) / 2;
if (key < sortedArray[mid]) {
upB = mid - 1;
} else if (key > sortedArray[mid]) {
lowB = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
location= bs.B_Search(numbers, a);
if(location != -1){
System.out.println("Find , at index of: "+ location);
}
else{
System.out.println("Not found!");
}
}
}
// 输出: a=14
没有找到!!
为什么?
【问题讨论】:
-
@rgettman 只有这一次对数组进行排序:D
-
@MarounMaroun 我的数组已排序!
-
@MarounMaroun 你能告诉我我的错误是什么吗?
-
仍然基本上是原始问题的完全欺骗,因为代码具有与此相同的缺陷。
标签: java binary-search