| Shape | Calls per call | Example | Typical cost |
|---|---|---|---|
| linear | one, shrinking by 1 | sum, factorial, walking a linked list | O(n) time, O(n) stack |
| halving | one, on half | powFast, binary search | O(log n) time and stack |
| multiple (tree) recursion | two or more | naïve Fibonacci, climbing stairs, subsets | often O(2ⁿ) — Ch 7 fixes many |
| divide and conquer | split into parts, solve each, combine | merge sort, quicksort | often O(n log n) |
| structural | one per child | folders, trees, graphs (DFS) | O(number of nodes) |
Recursive binary search — the halving shape (the full technique is in Binary Search (coming soon)):
static int binarySearch(int[] a, int target, int lo, int hi) {
if (lo > hi) return -1; // empty range → not found
int mid = lo + (hi - lo) / 2; // overflow-safe midpoint (01_java_basics.md Ch 3)
if (a[mid] == target) return mid;
return a[mid] < target
? binarySearch(a, target, mid + 1, hi)
: binarySearch(a, target, lo, mid - 1);
}
// {10, 20, 30, 40, 50, 60, 70}: found 60 at 5, 35 -> -1Helper methods. The public method often has a clean signature, and a private recursive helper carries the extra state (indexes, depth, results so far):
public static int binarySearch(int[] a, int target) {
// what callers see
return binarySearch(a, target, 0, a.length - 1); // the recursive helper does the work
}Returning values vs an accumulator. Two styles for collecting results:
Return and combine — each call returns its part (
countNotes). Clean; no shared state.Accumulator parameter — pass a list (or
StringBuilder) down and add to it (subsetsin Ch 6). Efficient when results are big.
Tail recursion. A call is a tail call when it's the very last thing the method does (return binarySearch(...) — nothing happens after it returns).
Some languages turn tail calls into loops automatically so they use no extra stack (tail-call optimisation). Java does not — every Java recursive call adds a
frame, tail call or not. So deep linear recursions in Java must be rewritten as loops (Ch 8).
Check yourself
3 questionsWhich shape is merge sort? What's its usual cost?
Show answerHide answer
Divide and conquer; O(n log n).
Why use a helper method?
Show answerHide answer
To keep a clean public signature while the recursive version carries extra parameters (indexes, accumulators).
Is return a[i] + sum(a, i + 1); a tail call? Does Java optimise tail calls?
Show answerHide answer
No — the addition happens after the recursive call returns. And no, Java never performs tail-call optimisation.