Code review requested to make this code simpler, cleaner, and better. Input array is sorted.
This program finds the greatest number smaller than x
. So, in an array [10 20 30 40]
and x = 25
, the output should be 20.
public class GreatestValueLesserThanEqualToX {
public static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x) {
if (arr == null) {
throw new NullPointerException(" The input array is null. ");
}
if (arr.length >= 1) {
return findGreatestValueLesserThanOrEqualToX (arr, x, 0, arr.length - 1);
} else {
return null; // note the difference wrt greatest value lesser than X.
}
}
private static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x, int lb, int ub) {
assert arr != null;
final int mid = (lb + ub) / 2;
/**
* Testing boundaries.
*/
// testing lower boundary.
if (mid == 0) {
if (arr[mid] > x) {
return null;
}
// single element array with value lesser than input value.
if (arr.length == 1) {
return arr[0];
}
}
//testing higher boundary.
if (lb == (arr.length - 1) && arr[mid] < x) {
return arr[mid];
}
/**
* Testing equalities and duplicates.
*/
// testing equality and duplicates. eg: consider input like: 1, 2, 2, 5
if (arr[mid] == x || arr[mid + 1] == x) {
return x;
}
/**
* Testing when element is in the range of array elements.
*/
// input x in range of array elements.
if (arr[mid] < x && arr[mid + 1] > x) {
return arr[mid]; // note the difference wrt greatest value lesser than X.
}
if (arr[mid] < x) {
return findGreatestValueLesserThanOrEqualToX (arr, x, mid + 1, ub);
} else {
return findGreatestValueLesserThanOrEqualToX (arr, x, lb, mid);
}
}
}