[英]How to binary search in an array which is in an descending order?
my code doesn't work, I want to be able to binary search in an array which is in an descending order. 我的代码不起作用,我希望能够以降序对数组进行二进制搜索。
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;
}
What might be it's problems and what am I not seeing? 可能是什么问题,我没看到什么?
Try foll
instead. 尝试使用foll
代替。
Assumption: a
is your array, i = start
, j= end
, x
is the element you're trying to find. 假设: a
是您的数组, i = start
, j= end
, x
是您要查找的元素。 Foll
will return -1
if x
not in a
如果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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.