Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
Basic Implementation
Basic.java
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);
}
}
Complexity
- Time: O(log n)
- Space: O(log n) call stack
Implementation notes
- Java stores the sorted input in a primitive
int[], and each recursivesearchcall receives the same array reference plus primitivetarget,lo, andhiparameters. - The base case
if (lo > hi) return -1;stops an empty search window. The midpoint useslo + (hi - lo) / 2, keeping the arithmetic overflow-safe before the checkedarr[mid]read. - On a match, the method returns
midimmediately. Otherwise it returns the recursive right callsearch(arr, target, mid + 1, hi)whenarr[mid] < target, or the left callsearch(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), wherearr[5] == 11returns5. Aside from normal stack frames and the initial array, the search uses primitive locals and creates no ongoing JVM GC pressure.
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.