JAVA里二分查找法 相关疑问
发布网友
发布时间:2022-04-19 19:43
我来回答
共2个回答
热心网友
时间:2022-04-14 07:15
没必要用递归,用循环就可以了。参考Arrays.binarySearch 的源码吧
public class binarySearch {
static int binarySearch(int[] d, int l, int h, int v) {
int low = l;
int high = h - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = d[mid];
if (midVal < v)
low = mid + 1;
else if (midVal > v)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("请输入键值");
int t = sc.nextInt();
int[] data = { 12, 13, 24, 35, 44, 67, 78, 98 };
int i = binarySearch(data, 0, data.length, t);
if (i > 0)
System.out.println("查找到值:" + t + "(" + i + ")");
else
System.out.println("没有查找到值:" + t);
sc.close();
System.exit(0);
}
}
热心网友
时间:2022-04-14 08:33
static int binarySearch(int[] d, int l, int h, int v) {
if (l > h)
return -1;
else {
int m = (l + h) / 2;
if (v == d[m])
return m;
else if (v < d[m])
return binarySearch(d, l, m, v); // l-m 改成m
else
return binarySearch(d, m, h, v); // m+l 改成m
}
}
你的二分搜索代码写错了。修改见注释