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.

JavaData Fetching

Code

javasnippet
17 lines
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

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.