In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than
public static int search(int target, int[] arr) {
if (arr == null || arr.length == 0)
return -1;
int lower = 0, higher = arr.length - 1, last = -1;
while (lower <= higher) {
int mid = lower + (higher - lower) / 2;
if (target == arr[mid]) {
last = mid;
lower = mid + 1;
} else if (target < arr[mid]) {
higher = mid - 1;
} else {
lower = mid + 1;
}
}
return (last > -1 && last < arr.length - 1) ? last + 1 : -1;
}
If we find 'target == arr[mid]', then any previous element would be either less than or equal to target. Hence, lower boundary is set as 'lower=mid+1'. Also, 'last' is the last index of 'target'. Finally we return 'last+1' - taking care of boundary conditions.