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));
}
}Inside the snippet
Binary Search Variant With Lower Bound (Java) comes down to the class LowerBound and the functions lowerBound and main.
Repetition is confined to while (lo < hi) — the rest of the file is straight-line.
Using it
Entry signature: public static int lowerBound(int[] arr, int target)
Treat main as the orchestrator calling lowerBound in a fixed order.
Key statements
if (arr[mid] < target) lo = mid + 1;
int[] arr = {1, 2, 2, 3, 4, 6};
int lo = 0, hi = arr.length;
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- How do you run Binary Search Variant With Lower Bound (Java)?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.