gpt4 book ai didi

Java 二进制搜索

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:33 24 4
gpt4 key购买 nike

我能得到一些帮助吗?我已经尝试了很多方法来让它工作我对数组进行了排序并打印但是之后我的二进制搜索功能不想运行并给我正确的结果。它总是给我-1。有帮助吗?

public class BinarySearch {
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] a, double key) {
int low = 0;
int high = a.length -1;
int mid;
while (low<=high) {
mid = (low+high) /2;
if (mid > key)
high = mid -1;
else if (mid < key)
low = mid +1;
else
return mid;
}
return NOT_FOUND;
}
public static void main(String[] args) {
double key = 10.5, index;
double a[] ={10,5,4,10.5,30.5};
int i;
int l = a.length;
int j;
System.out.println("The array currently looks like");
for (i=0; i<a.length; i++)
System.out.println(a[i]);
System.out.println("The array after sorting looks like");
for (j=1; j < l; j++) {
for (i=0; i < l-j; i++) {
if (a[i] > a[i+1]) {
double temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
for (i=0;i < l;i++) {
System.out.println(a[i]);
}
System.out.println("Found " + key + " at " + binarySearch(double a[], key));
}
}

最佳答案

您实际上并不是在与数组值进行比较。在

while (low <= high) {
mid = (low + high) / 2;
if (mid > key) {
high = mid - 1;
} else if (mid < key) {
low = mid + 1;
} else {
return mid;
}
}

改为使用此部分

    while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > key) {
high = mid - 1;
} else if (a[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}

你找到索引是正确的,但你所做的只是将索引号与你的键进行比较,这显然是不正确的。当您编写 a[mid] 时,您实际上会将您的 key 与索引 mid 处的数字进行比较。

另外最后一行代码编译报错,应该是

System.out.println("Found " + key + " at " + binarySearch(a, key));

关于Java 二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12517764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com