J.A.R.E.D
J.A.R.E.D

Reputation: 59

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?

Upvotes: 0

Views: 1477

Answers (1)

D.M.
D.M.

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

Related Questions