Reputation: 59
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?
Upvotes: 0
Views: 1477
Reputation: 41
Try foll
instead.
Assumption: a
is your array, i = start
, j= end
, x
is the element you're trying to find. Foll
will return -1
if x
not in a
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;
}
Upvotes: 1