我的代码不起作用,我希望能够在降序排列的数组中进行二分搜索。
static int searchDescendingGT( double[] a, int i, int j, double x )
{
while(i!=j){
// | >x | unknown | >=x |
int m = i+(j-i)/2;
if (a[m]<x){
j = m;
}
else{
i = m+1;
}
}
return i;
}
它可能存在什么问题以及我没有看到什么?
最佳答案
尝试follow
。
假设:a
是你的数组,i = start
,j= end
,x
是元素你正在努力寻找。如果 x
不在 a
Foll
将返回 -1
static int searchDescendingGT(double[] a, int i, int j, double x) {
while (i <= j) {
int m = (i + j) / 2;
if (a[m] == x) {
return m;
} else if (a[m] < x) {
j = m - 1;
} else {
i = m + 1;
}
}
return -1;
}
关于java - 如何在降序排列的数组中进行二分查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36826661/