The following code should return he closest value to a input number 'x' in the sorted array. The while loop is guaranteed to return. But the compiler understandably forces me to return a value. My question is about best practice involved. What is the general convention used such cases where return statement is forced by compiler ? ie throw exception ? return default ? etc ?
NOTE: I have selected "IllegalArgumentException"
http://codereview.stackexchange.com/questions/47328/find-the-value-nearest-to-k-in-the-sorted-array. I dont have any answer to select, but Thank all for insight. I am not aware about SO protocols in such cases
/**
* Given a sorted array returns the 'closest' element to the input 'x'.
* 'closest' is defined as Math.min(Math.abs(x), Math.abs(y))
*
* Expects a sorted array, and if array is not sorted then results are unpredictable.
*
* @param a The sorted array a
* @return The nearest element
*/
public static int getClosestK(int[] a, int x) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
// test lower case
if (mid == 0) {
if (a.length == 1) {
return a[0];
}
return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x;
}
// test upper case
if (mid == a.length - 1) {
return a[a.length - 1];
}
// test equality
if (a[mid] == x || a[mid + 1] == x) {
return x;
}
// test perfect range.
if (a[mid] < x && a[mid + 1] > x) {
return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x;
}
// keep searching.
if (a[mid] < x) {
low = mid + 1;
} else {
high = mid;
}
}
// return a[0]; ?????
}