Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    Shapes of Recursion

    Recursive binary search — the halving shape (the full technique is in 02DSA/01Concepts/07binarysearch.md):

    Chapter 5 of 93 min read

    ShapeCalls per callExampleTypical cost
    linearone, shrinking by 1sum, factorial, walking a linked listO(n) time, O(n) stack
    halvingone, on halfpowFast, binary searchO(log n) time and stack
    multiple (tree) recursiontwo or morenaïve Fibonacci, climbing stairs, subsetsoften O(2ⁿ) — Ch 7 fixes many
    divide and conquersplit into parts, solve each, combinemerge sort, quicksortoften O(n log n)
    structuralone per childfolders, trees, graphs (DFS)O(number of nodes)

    Recursive binary search — the halving shape (the full technique is in Binary Search (coming soon)):

    Java
    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 -> -1

    Helper methods. The public method often has a clean signature, and a private recursive helper carries the extra state (indexes, depth, results so far):

    Java
    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 (subsets in 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 questions
    1

    Which shape is merge sort? What's its usual cost?

    Show answer

    Divide and conquer; O(n log n).

    2

    Why use a helper method?

    Show answer

    To keep a clean public signature while the recursive version carries extra parameters (indexes, accumulators).

    3

    Is return a[i] + sum(a, i + 1); a tail call? Does Java optimise tail calls?

    Show answer

    No — the addition happens after the recursive call returns. And no, Java never performs tail-call optimisation.