Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.

Algorithm

execution replay The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison This Java DSA version keeps the same data and final output as every other DSA book in this wave.

Basic Implementation

Basic.java
Replay: real traced execution (multi-file project)
public class Basic {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13};
        int target = 11;
        System.out.println(search(arr, target, 0, arr.length - 1));
    }

    static int search(int[] arr, int target, int lo, int hi) {
        if (lo > hi) {
            return -1;
        }
        int mid = lo + (hi - lo) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            return search(arr, target, mid + 1, hi);
        }
        return search(arr, target, lo, mid - 1);
    }
}
  1. lo ← 0, hi ← 6, target ← 11

    1public class Basic {2    public static void main(String[] args) {
    values this step0lo6hi11target
  2. mid ← 3, arr[mid] ← 7, next call ← (4, 6)

    11}12int mid = lo + (hi - lo) / 2;13if (arr[mid] == target) {
    values this step3mid7arr[mid](4, 6)next call0lo6hi
  3. mid ← 5, arr[mid] ← 11, result ← 5

    11}12int mid = lo + (hi - lo) / 2;13if (arr[mid] == target) {
    values this step5mid11arr[mid]5result4lo6hi
  4. stdout ← 5

    4    int target = 11;5    System.out.println(search(arr, target, 0, arr.length - 1));6}
    values this step5stdout5result

Complexity

  • Time: O(log n)
  • Space: O(log n) call stack

Implementation notes

  • Java stores the sorted input in a primitive int[], and each recursive search call receives the same array reference plus primitive target, lo, and hi parameters.
  • The base case if (lo > hi) return -1; stops an empty search window. The midpoint uses lo + (hi - lo) / 2, keeping the arithmetic overflow-safe before the checked arr[mid] read.
  • On a match, the method returns mid immediately. Otherwise it returns the recursive right call search(arr, target, mid + 1, hi) when arr[mid] < target, or the left call search(arr, target, lo, mid - 1) for larger values, so the found index propagates back through the call stack.
  • The replay-visible calls go from window (0, 6) to (4, 6), where arr[5] == 11 returns 5. Aside from normal stack frames and the initial array, the search uses primitive locals and creates no ongoing JVM GC pressure.