Searching
Binary Search (Recursive)
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);
}
}
lo ← 0, hi ← 6, target ← 11
1public class Basic {2 public static void main(String[] args) {values this step0lo6hi11targetmid ← 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 call0lo6himid ← 5, arr[mid] ← 11, result ← 5
11}12int mid = lo + (hi - lo) / 2;13if (arr[mid] == target) {values this step5mid11arr[mid]5result4lo6histdout ← 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 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.