Binary Search Variant With Lower Bound (Java)
Find the leftmost position where a sorted Java array can accept a target using a binary search lower bound variant.
Code
public class LowerBound {
public static int lowerBound(int[] arr, int target) {
int lo = 0, hi = arr.length;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (arr[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 6};
System.out.println(lowerBound(arr, 2));
System.out.println(lowerBound(arr, 5));
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.