0

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?

J.A.R.E.D
  • 61
  • 8
  • 1
    Possible duplicate of [Binary search in a sorted (memory-mapped ?) file in Java](http://stackoverflow.com/questions/736556/binary-search-in-a-sorted-memory-mapped-file-in-java) – pczeus Apr 24 '16 at 18:44

1 Answers1

1

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;

}
D.M.
  • 41
  • 3