/**
*
* @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;
}
Asked
Active
Viewed 90 times
0

Debasish Bhol
- 19
- 4
-
Yes, `mid` is a `long`. Array indices are only ever `int`. – Andy Turner Jul 15 '19 at 08:02
-
What is the question here? – Amongalen Jul 15 '19 at 08:04
-
I'm getting lossy conversion error. – Debasish Bhol Jul 15 '19 at 08:15
1 Answers
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