Ketan G - 1 year ago 103

Java Question

I am getting one compilation error in binary search recursive implementation

Here is my method:

`public static int binarySearch(int[] a, int start, int end, int x) {`

if (start > end) {

return -1;

}

int mid = (start + end) / 2;

if (a[mid] == x) {

return mid;

} else if (a[mid] > x) {

binarySearch(a, start, mid - 1, x);

} else {

binarySearch(a, mid + 1, end, x);

}

}

I am giving two base case for this and returning two int values, but still i am getting error why this is happening . Any related thoughts'd be apprecited.

Thanks

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

What do you think gets returned on the first call if both `start > end`

and `a[mid] == x`

are `false`

?

You need to return your recursive calls as well so that the found value (or `-1`

) will propagate back through the recursion stack frames:

```
public static int binarySearch(int[] a, int start, int end, int x) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
return binarySearch(a, start, mid - 1, x); // return here
} else {
return binarySearch(a, mid + 1, end, x); // return here
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**