0
/**
 * 
 * @param b is an array
 * @param x is the element for which I want to search the lower bound
 * @param n is the length of the array
 * @return high if element not found or mid - 1 if found
 */

static long searchMe(long b[], long x, long n){
    long low = 0, high = n, mid=0;
    while(low<=high){
        mid = (low+high)/2;
        if(b[mid] == x){
            if(mid > 0 && b[mid-1] == x) high = mid-1;
            else return mid-1;
        }
        else if(b[mid] < x) low = mid + 1;
        else high = mid - 1;
    }
    // System.out.println(low + " == " + high);
    return high;
}

1 Answers1

0

You are using mid as an index of an array, but mid is long. The index of an array is always an int. You can try this.

static long searchMe(long b[], long x, long n) {
    long low = 0, high = n;
    int mid = 0; // CHANGED FROM long TO int
    while (low <= high) {
        mid = (int) ((low + high) / 2); // CAST to int
        if (b[mid] == x) {
            if (mid > 0 && b[mid - 1] == x)
                high = mid - 1;
            else
                return mid - 1;
        } else if (b[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
    // System.out.println(low + " == " + high);
    return high;
}
Mark Melgo
  • 1,477
  • 1
  • 13
  • 30