Computer Fundamentals and Introduction to Programming · Lecture Notes
Chapter 12: Recursion
Some problems contain a smaller copy of themselves. 4! is 4 times 3!, and 3! is 3 times 2!. A method that solves such a problem can hand the smaller part of the work back to itself. A method that calls itself is called recursive, and the technique is called recursion. These notes first introduce the two parts every recursive method needs, the base case and the recursive case. They then follow, step by step, how pending calls pile up in memory, which is the call stack. After examples such as sums, digit sums, palindromes, the greatest common divisor, exponentiation, binary search, merge sort, the Towers of Hanoi and subset generation, the notes turn to cost. Numbers show when recursion is more expensive than a loop, why the Fibonacci example repeats the same work thousands of times, and how memoization removes that repetition. Every Java program was compiled and run with JDK 21, and the outputs, call counts and stack depths in the notes come from those runs.
Learning outcomes
- Structure
- Identify the base case and the recursive case of a recursive method; explain what measure shrinks with each call and why the base case is always reached.
- Tracing
- Trace a recursive call step by step on the call stack; tell which work happens on the way down and which on the way back; find the number of frames on the stack at its deepest point.
- Comparison
- Compare a recursive solution with a loop in time, extra memory and readability; explain the causes of stack overflow and integer overflow.
- Improvement
- Find repeated subproblems in a recursion tree; use memoization to reduce the number of calls from exponential to linear; explain why tail recursion does not shrink the stack in Java.
12.1What is recursion?
12.1.1A method that calls itself
Methods can call one another. main calls a method, and that method may call another. When the called method finishes, control returns to the caller and the program continues where it left off. In Java, the methods a method may call include the method itself: a method can use its own name inside its own body.
At first this looks odd: a method that calls itself seems as if it could never finish. The picture changes if every call is made on a slightly smaller version of the problem. As the problem shrinks, it eventually becomes small enough that the answer is known directly. At that point the method does not call itself again; it returns the answer immediately. The waiting calls then use that answer, one after another, to finish their own work.
Recursion is the technique in which a method reduces a problem to a smaller instance of the same problem and calls itself to solve it. A method that calls itself is a recursive method.
Factorial illustrates the idea well. In mathematics, 4! = 4 × 3 × 2 × 1 = 24. The same product can be written 4! = 4 × 3!, so to find 4! it is enough to find 3! first. Computing 3! needs 2!, and 2! needs 1!. The value 1! is known directly: it is 1. Figure 12.1 shows this nesting. Each box contains a smaller copy of the one before it, and the innermost box does not open another box inside itself.
Each call works with its own parameters and its own local variables. The n in the factorial(4) call and the n in the factorial(3) call have the same name but are separate variables: one holds 4, the other 3. Java reserves a separate area of memory for every call. This area is called a stack frame, and frames are stacked on top of one another in the order the calls were made. The structure formed by the frames is the call stack. The call stack is the key to understanding recursion, and the notes rely on it throughout.
A stack frame is the area of memory set up for one method call. It holds the call's parameters, its local variables and the place to return to when it finishes. The frames of all the calls currently running sit on top of one another in the call stack. The frame of a new call is added on top; when the call finishes, the top frame is removed.
12.1.2The two required parts
Every correct recursive method has two parts. One is the case in which the answer is known directly. The other is the case in which the problem is reduced and the method calls itself again.
The base case is the case in which the result is known directly and no new call is made. For factorial, the result is 1 when n ≤ 1. The recursive case is the case in which the problem is turned into a smaller instance and the method calls itself. For factorial, this is the computation n × factorial(n − 1).
Figure 12.2 shows the order of these two parts within a call. When a call starts, it first asks whether this is the base case. If the answer is yes, the result is returned at once. If it is no, the problem is reduced and a new call is made. The new call starts with the same question.
If either part is missing, the method does not work correctly. Without a base case the calls never stop: every call opens a new frame, and sooner or later memory runs out. With a base case but a problem that does not get closer to it on every call, the outcome is the same. In the line return n * factorial(n);, for example, n never shrinks and the base case is never reached.
For this reason, three questions are asked when writing a recursive method:
- What is the base case? Which is the smallest input whose answer is known without computation? For factorial it is n ≤ 1.
- How does the problem shrink? Which measure decreases on every call? For factorial, n decreases by 1 on every call.
- How does the small answer become the big answer? What is done with the result of the subcall? For factorial, the subresult is multiplied by n.
The answer to the second question is also the reason the method terminates. Here n is an integer and decreases by 1 on every call. Starting from 4, n reaches 1 in at most three steps. A decreasing integer reaches a lower bound in a finite number of steps, and this is how we show that the base case can be reached.
Writing the base case so that it skips some inputs. The method if (n == 0) return 0; return n + f(n - 2); works for even n. In the call f(5), however, n takes the values 5, 3, 1, −1, −3, and so on. None of the odd numbers equals 0, so the base case is skipped and the calls continue. Changing the condition to n <= 0 fixes this. When the input shrinks in jumps, a “less than or equal” test is safer than a test for equality.
12.1.3Thinking recursively
When writing a recursive method, there is no need to picture all the calls at once. Instead, think this way: “The method already works correctly for every input smaller than this one. Given that assumption, how do I build the answer for the input I was given?” For factorial the answer is short. If factorial(n − 1) gives the correct result, then n! is n times that result.
This way of thinking resembles induction in mathematics. In induction, the claim is first shown for the smallest case. Then, assuming the claim holds for k, it is shown to hold for k + 1. The base case corresponds to the starting step of induction, and the recursive case to the inductive step. If both steps are correct, the method returns the correct result for every valid input.
Even so, the safest way for a beginner is to trace the method by hand on a small input. Which call is opened when, what it waits for and what it returns are written in a table. In the rest of these notes nearly every example is traced with such a table. All the tables were produced on JDK 21 by adding lines to the methods that record the moments of call and return.
12.2Factorial and the call stack
12.2.1Recursive factorial
The mathematical definition of factorial takes two lines: 0! = 1! = 1 and n! = n × (n − 1)!. The factorial of a negative number is not defined. The Java method follows this definition almost word for word:
static long factorial(int n) {
if (n < 0)
throw new IllegalArgumentException();
if (n <= 1) return 1;
return n * factorial(n - 1);
}The method works line by line as follows:
static long factorial(int n): the method takes anintand returns along. Factorial grows very fast, so the result type islong. An int can hold at most 12!; a long is enough up to 20!.if (n < 0) throw new IllegalArgumentException();: a negative input is invalid. In this case the method throws an exception object and stops running. Throwing is Java's way for a method to say “I cannot do the job with this input.”if (n <= 1) return 1;: the base case. For 0 and 1 the result is 1, and no new call is made.return n * factorial(n - 1);: the recursive case. First factorial(n − 1) is called. When that call finishes and returns a value, the value is multiplied by n and the product is returned.
The order in the last line matters. The multiplication cannot be done until the result of the subcall arrives, so factorial(4) leaves its multiplication half finished and waits. The factorial(3) call waits in the same way. All the multiplications happen on the way back.
Figure 12.3 shows, on a number line, what the method does depending on the region the input falls in. Negative numbers are in the error region. 0 and 1 are the base case. From 2 upward lies the recursive region; each call moves one step to the left and finally lands in the base case.
Run on a few inputs, the method gives the expected results. The first line of the output below shows factorial(4), factorial(0), factorial(1) and factorial(20). The second line shows the exception thrown by the call factorial(−3), caught and printed:
24 1 1 2432902008176640000
factorial(-3): java.lang.IllegalArgumentException12.2.2Tracing factorial(4) step by step
The trace slide in the presentation uses the program below. The main method calls factorial(4) and prints the result:
static long factorial(int n) {
if (n < 0)
throw new IllegalArgumentException();
if (n <= 1) return 1;
return n * factorial(n - 1);
}
System.out.println(factorial(4));24Table 12.1 gives, step by step, what happens on the call stack while the program runs. The “Frames” column is the number of frames on the stack at that moment, and it includes the frame of main.
| Step | Event | Frames (including main) | Stack (bottom to top) | Explanation |
|---|---|---|---|---|
| 1 | factorial(4) called | 2 | main, f(4) | waits for 4 × factorial(3) |
| 2 | factorial(3) called | 3 | main, f(4), f(3) | waits for 3 × factorial(2) |
| 3 | factorial(2) called | 4 | main, f(4), f(3), f(2) | waits for 2 × factorial(1) |
| 4 | factorial(1) called | 5 | main, f(4), f(3), f(2), f(1) | base case |
| 5 | factorial(1) returned | 5 | main, f(4), f(3), f(2), f(1) | return 1 |
| 6 | factorial(2) returned | 4 | main, f(4), f(3), f(2) | 2 × 1 = 2 |
| 7 | factorial(3) returned | 3 | main, f(4), f(3) | 3 × 2 = 6 |
| 8 | factorial(4) returned | 2 | main, f(4) | 4 × 6 = 24 |
| 9 | main prints the result | 1 | main | 24 |
The first four rows of the table are the descent phase. factorial(4) is called and a frame is opened. In this frame n = 4. Since 4 < 0 and 4 ≤ 1 are both false, execution reaches the last line. The multiplication needs the result of factorial(3), so this frame goes into a wait and a new call is made. The same happens for n = 3 and n = 2. In step 4, factorial(1) is called. In this frame 1 ≤ 1 is true: the base case has been reached.
The stack is now at its deepest. With main and four factorial frames there are 5 frames in total, and no multiplication has been performed yet. Each frame keeps its own value of n and waits for the result of the call above it. The upper part of Figure 12.4 shows this moment.
After step 5 the returning phase begins. factorial(1) returns 1 and its frame is removed. Control passes to the frame of factorial(2), which now has the value it was waiting for: 2 × 1 = 2 is computed and returned. With that value factorial(3) computes 3 × 2 = 6, and factorial(4) computes 4 × 6 = 24. Finally main prints 24.
Two conclusions follow from this trace. First, frames are closed in the reverse of the order in which they were opened. The last frame opened, factorial(1), closes first; the first one opened, factorial(4), closes last. This behavior is the “last in, first out” (LIFO) rule, and it is where the stack data structure gets its name. Second, in a call to factorial(n) there are n factorial frames on the stack at the same time. The extra memory grows in proportion to n, that is, it is O(n). For factorial(20), a version with a counter measured 20 calls and a maximum depth of 20 frames.
Believing that the multiplication happens while the calls are being made. Because the line return n * factorial(n - 1); reads from left to right, one might think the product 4 × 3 × 2 × 1 is formed in that order. But the second factor of the multiplication does not exist yet. The first multiplication to complete is 2 × 1, then 3 × 2, and 4 × 6 comes last. If, while tracing the call stack, you ask of each frame “what is this frame waiting for?”, the order does not get confused.
12.2.3Descent and return
A recursive computation can be thought of in two phases. In Figure 12.5, the left column is the descent phase: the calls open downward and the stack grows. The right column is the returning phase: values are carried upward and the stack shrinks.
In the descent phase each call only asks a question and starts the next call. The real computation happens in the returning phase. This distinction is very useful when predicting the output of a recursive method. A print statement placed before the recursive call runs while descending. One placed after the call runs while returning, that is, in reverse order. By moving the print line, the same method can print the digits of a number in forward or reverse order.
The method below prints n while n > 0, calls itself with n − 2, and prints n again on the way back:
static void g(int n) {
if (n <= 0) return;
System.out.print(n + " ");
g(n - 2);
System.out.print(n + " ");
}In the call g(5), 5, 3 and 1 are printed while descending. g(−1) is the base case and returns without printing anything. In the returning phase the frames close in reverse order and 1, 3, 5 are printed. The JDK 21 output is 5 3 1 1 3 5. The output looks like a mirror: the first half shows the descent and the second half shows the returning.
12.3Single-call examples
In factorial, each call makes at most one new call. The calls of such methods form a single chain: f(4) → f(3) → f(2) → f(1). This shape is called linear recursion. All five examples in this section are linear. In each of them the same three questions are asked: what is the base case, how does the problem shrink, and how is the subresult used?
12.3.1The sum from 1 to n
The sum of the numbers from 1 to n can be defined like factorial. sum(n) is n plus sum(n − 1). If there are no numbers, the sum is 0: sum(0) = 0. So sum(3) = 3 + sum(2) = 3 + 2 + sum(1) = 3 + 2 + 1 + sum(0) = 6.
static int sum(int n) {
if (n <= 0) return 0;
return n + sum(n - 1);
}
System.out.println(sum(3));6The base case is written as n <= 0. This choice makes the method safe for negative inputs as well. The call sum(−5) enters the base case at the first test and returns 0. If the condition were n == 0, then in the call sum(−5) n would go down through −6, −7, … and the calls would never stop.
| Step | Event | Frames (including main) | Explanation |
|---|---|---|---|
| 1 | sum(3) called | 2 | 3 <= 0 → false; waits for 3 + sum(2) |
| 2 | sum(2) called | 3 | 2 <= 0 → false; waits for 2 + sum(1) |
| 3 | sum(1) called | 4 | 1 <= 0 → false; waits for 1 + sum(0) |
| 4 | sum(0) called | 5 | 0 <= 0 → true |
| 5 | sum(0) returned | 5 | return 0 |
| 6 | sum(1) returned | 4 | 1 + 0 = 1 |
| 7 | sum(2) returned | 3 | 2 + 1 = 3 |
| 8 | sum(3) returned | 2 | 3 + 3 = 6 |
| 9 | main prints 6 | 1 |
Table 12.2 closely resembles the factorial trace. In the descent phase four sum frames are opened: sum(3), sum(2), sum(1) and sum(0). At the deepest moment there are 5 frames including main. sum(0) returns 0. On the way back, 1 + 0 = 1, 2 + 1 = 3 and 3 + 3 = 6 are computed in turn. The result is 6 = 3 + 2 + 1 + 0.
The method sum(n) makes n + 1 calls and the stack gets n + 1 frames deep. Both time and extra memory are O(n). The same sum can be found in a single step with the formula n(n + 1)/2. This example was chosen to show the mechanism of recursion; it is not the best way to compute a sum.
12.3.2Digit sum and a helper method
The digit sum of a number can also be written recursively. The idea rests on the pattern of digits: n % 10 gives the last digit, and n / 10 drops the last digit. The digit sum of 472 is the last digit 2 plus the digit sum of 47. The digit sum of a one-digit number is the number itself. These sentences give both the base case and the recursive case of the method.
static int digitSum(int n) {
long m = Math.abs((long) n);
return digitSumPos(m);
}
static int digitSumPos(long n) {
if (n < 10) return (int) n;
return (int) (n % 10)
+ digitSumPos(n / 10);
}
System.out.println(digitSum(472));The program prints 13. The code has two methods. The one that does the real work is digitSumPos, and it is correct only for non-negative numbers. digitSum is the method called from outside: it prepares the input and leaves the real work to the helper. Such a method is called a helper method.
Why is the preparation step needed? For a negative number, n % 10 is negative. In Java, for example, −472 % 10 = −2. Also, because −472 < 10 is true, the method would enter the base case at once and return −472. To prevent this, the absolute value is taken first. Why is the absolute value taken after converting to long? The smallest int value is −2,147,483,648, while the largest is 2,147,483,647. As a result, Math.abs(Integer.MIN_VALUE) does not fit in an int and again returns −2,147,483,648. Math.abs((long) n), on the other hand, correctly gives 2,147,483,648. For this reason the helper takes a long parameter.
The program was also run on a few edge inputs. The second line of the output holds the results of digitSum(−472), digitSum(0) and digitSum(Integer.MIN_VALUE):
13
13 0 47The last value is 47: 2 + 1 + 4 + 7 + 4 + 8 + 3 + 6 + 4 + 8 = 47. If the absolute value were taken with int, the method would reach the base case with a negative number and return a wrong result.
| Frame | Condition | n % 10 | n / 10 | Result |
|---|---|---|---|---|
| digitSumPos(472) | 472 < 10 → false | 2 | 47 | waits |
| digitSumPos(47) | 47 < 10 → false | 7 | 4 | waits |
| digitSumPos(4) | 4 < 10 → true | — | — | return 4 |
| digitSumPos(47) | return | 7 | 4 | 7 + 4 = 11 |
| digitSumPos(472) | return | 2 | 47 | 2 + 11 = 13 |
| digitSum(472) | — | — | — | return 13 |
Table 12.3 shows which digit each frame holds back. The frame for 472 holds back the 2, and the frame for 47 holds back the 7. The number 4 has one digit and is the base case. On the way back, 7 + 4 = 11 is computed, then 2 + 11 = 13. The helper method returns 13, and digitSum passes this value on unchanged.
The stack depth equals the number of digits in the number. The number of digits grows logarithmically with the size of the number: an int with 10 digits opens at most 10 helper frames. So digit problems carry no risk of stack overflow.
12.3.3Palindrome check
A palindrome is a string that reads the same backward as forward, such as “kayak”, “ana” or “abba”. Whether a string is a palindrome can be found by moving inward from both ends. If the first and last characters differ, the string is not a palindrome. If they are the same, these two characters are dropped and the remaining inner string is checked with the same question. If a single character or no character is left in the middle, the string is a palindrome.
static boolean isPal(String s,
int left, int right) {
if (left >= right) return true;
if (s.charAt(left) != s.charAt(right))
return false;
return isPal(s, left + 1, right - 1);
}
System.out.println(isPal("kayak", 0, 4));The method does not make a copy of the string. Instead it describes the region to examine with two indices, left and right. On each call left increases by 1 and right decreases by 1. The measure of the problem is the length of the region, right − left + 1. This length drops by 2 on every call and ends up 1 or 0. The base case left >= right covers both of these situations.
The method has two separate exits. If the ends differ, it returns false; this also counts as a base case, because no new call is made. If the ends are equal, the result of the call in the last line is returned unchanged. No computation is done on the way back.
| Frame | left >= right | Ends | Next step |
|---|---|---|---|
| isPal(s, 0, 4) | 0 >= 4 → false | 'k' equals 'k' | isPal(s, 1, 3) |
| isPal(s, 1, 3) | 1 >= 3 → false | 'a' equals 'a' | isPal(s, 2, 2) |
| isPal(s, 2, 2) | 2 >= 2 → true | — | return true |
According to Table 12.4, three calls are made for “kayak”. Characters 0 and 4 are 'k', and characters 1 and 3 are 'a'. In the third call 2 ≥ 2 is true: only 'y' is left in the middle and true is returned. This value passes through two frames and reaches main. For “kitap” a single call is enough. The first character is 'k' and the last is 'p', so the method returns false at once. The program was also run on extra inputs. The second line below holds the results for "kitap", "abba" and "a", in that order:
true
false true trueIn the even-length string "abba" the inner region finally becomes empty: in the call isPal(s, 2, 1), 2 ≥ 1 is true. Writing the base case with >= instead of equality catches this case too. For a string of n characters at most ⌊n/2⌋ + 1 calls are made; time and stack depth are O(n).
12.3.4GCD with Euclid's algorithm
The greatest common divisor (GCD) of two numbers is the largest number that divides both without a remainder. GCD(48, 18) = 6. Euclid's algorithm finds it using division remainders. It rests on this rule: if b is nonzero, GCD(a, b) = GCD(b, a mod b). If b = 0, GCD(a, 0) = |a|. These two lines directly describe a recursive method.
static int gcd(int a, int b) {
if (b == 0) return Math.abs(a);
return gcd(b, a % b);
}
System.out.println(gcd(48, 18));Why is the rule correct? Every number that divides both a and b also divides the difference a − k·b, and a mod b is such a difference. Conversely, every number that divides both b and a mod b also divides a. So the pairs (a, b) and (b, a mod b) have the same common divisors, and two pairs with the same common divisors have the same greatest common divisor.
| Frame | a | b | a % b | Next step |
|---|---|---|---|---|
| gcd(48, 18) | 48 | 18 | 12 | gcd(18, 12) |
| gcd(18, 12) | 18 | 12 | 6 | gcd(12, 6) |
| gcd(12, 6) | 12 | 6 | 0 | gcd(6, 0) |
| gcd(6, 0) | 6 | 0 | — | return 6 |
Table 12.5 shows four calls. 48 % 18 = 12, 18 % 12 = 6 and 12 % 6 = 0. gcd(6, 0) is the base case and returns 6. This value comes back unchanged through three frames. The last nonzero remainder, 6, is the GCD we were looking for.
The method was also tried on other inputs. The second line below holds the results of gcd(18, 48), gcd(17, 5), gcd(−12, 8) and gcd(7, 0):
6
6 1 4 7In the call gcd(18, 48), the first step swaps the numbers: since 18 % 48 = 18, the next call is gcd(48, 18). That is why the version with a counter counts 5 calls on this input, against 4 for gcd(48, 18). The Math.abs in the base case makes the result positive for negative inputs: gcd(−12, 8) = 4.
Euclid's algorithm is very fast. The remainders at least halve every two steps, so the number of calls is proportional to the number of digits of the inputs. The worst case occurs with two consecutive Fibonacci numbers. Even for 1,134,903,170 and 701,408,733, the largest consecutive Fibonacci pair that fits in an int, the version with a counter counted only 44 calls.
12.3.5Reversing a string
The reverse of a string can also be defined recursively. The reverse of “abc” is found by appending 'a' to the end of the reverse of “bc”. A string of length 0 or 1 is its own reverse.
static String reverse(String s) {
if (s.length() <= 1) return s;
return reverse(s.substring(1)) + s.charAt(0);
}
System.out.println(reverse("abc"));s.substring(1) gives the remaining string without the first character, and s.charAt(0) is the first character. The subcall returns the reverse of the rest, and the first character is appended to that result. The addition is between a String and a char, so the result is a String.
| Frame | Work | Return value |
|---|---|---|
| reverse("c") | length 1 ≤ 1 → base case | return "c" |
| reverse("bc") | reverse("c") + 'b' | "c" + 'b' = "cb" |
| reverse("abc") | reverse("bc") + 'a' | "cb" + 'a' = "cba" |
The program was also run on the empty string, “kayak” and “Java”:
cba
[] kayak avaJThe reverse of the empty string is the empty string; the square brackets are printed to make this visible. Because “kayak” is a palindrome, its reverse is the same as itself.
This method is short and readable but not efficient. Each call creates a new substring with substring. For a string of n characters, the total length of the substrings created is about n(n + 1)/2. For a string of 1000 characters, the version with a counter counted 1000 calls and substrings of 500,500 characters in total. The time is O(n²). Reversing with a loop and a StringBuilder takes O(n). A solution being short does not mean it is cheap.
12.4Exponentiation
12.4.1Plain recursive power
The n-th power of a base is the product of the base with itself n times. This definition can also be written recursively: baseⁿ = base × baseⁿ⁻¹ and base⁰ = 1. For example, 2⁴ = 2 × 2³.
static long power(long base, int n) {
if (n == 0) return 1;
return base * power(base, n - 1);
}
System.out.println(power(2, 4));16The structure is the same as for factorial. The base case is n == 0. In the recursive case n decreases by 1 and the subresult is multiplied by the base. The base stays the same on every call; only the exponent shrinks.
| Frame | Condition | Return value |
|---|---|---|
| power(2, 0) | 0 == 0 → true | return 1 |
| power(2, 1) | 1 == 0 → false | 2 × 1 = 2 |
| power(2, 2) | 2 == 0 → false | 2 × 2 = 4 |
| power(2, 3) | 3 == 0 → false | 2 × 4 = 8 |
| power(2, 4) | 4 == 0 → false | 2 × 8 = 16 |
In the call power(2, 4), the calls power(2, 3), power(2, 2), power(2, 1) and power(2, 0) are opened. power(2, 0) is the base case and returns 1. Table 12.7 gives the multiplications on the way back: 2, 4, 8 and 16. In total n + 1 = 5 calls are made. For power(2, 10) the number is 11. Time and stack depth are O(n).
What happens if the method is called with a negative exponent? In the call power(2, −1), n is −1 and −1 == 0 is false. In the next call n is −2, then −3. n moves away from zero and the base case is never reached. The calls continue until the stack is full. This case is examined with measurements in 12.11.2.
12.4.2Fast power
The plain method does 10 multiplications for 2¹⁰. But 2¹⁰ = (2⁵)². If 2⁵ is computed once and multiplied by itself, the work is halved. The same idea can be used for 2⁵: since the exponent is odd, one extra base is multiplied in: 2⁵ = (2²)² × 2. Because the exponent is halved at each step, the number of calls drops sharply. This method is called fast power, or exponentiation by squaring.
static long fastPow(long base, int exp) {
if (exp < 0) throw new IllegalArgumentException("exp < 0");
if (exp == 0) return 1;
long half = fastPow(base, exp / 2);
if (exp % 2 == 0) return half * half;
return half * half * base;
}
System.out.println(fastPow(2, 10));The first line rejects a negative exponent: because exp / 2 rounds toward zero for negative numbers, −1 / 2 would be 0, and the method would return a wrong result (1) without raising any error. The method then calls itself with exp / 2 and stores the result in the variable half. In Java, the quotient of two ints is an integer; 5 / 2 = 2. If the exponent is even, the result is half × half. If it is odd, a 1 was lost in the division and the result is multiplied by the base once more.
The variable half is the most important detail of this method. If the code were written as return fastPow(base, exp / 2) * fastPow(base, exp / 2);, the same subproblem would be computed twice. Every call would make two calls, and the gain would vanish completely. Computing the subresult once and keeping it in a local variable is what makes the method fast.
| Frame | exp / 2 | half | exp | Return value |
|---|---|---|---|---|
| fastPow(2, 0) | — | — | — | return 1 |
| fastPow(2, 1) | 0 | 1 | odd | 1 × 1 × 2 = 2 |
| fastPow(2, 2) | 1 | 2 | even | 2 × 2 = 4 |
| fastPow(2, 5) | 2 | 4 | odd | 4 × 4 × 2 = 32 |
| fastPow(2, 10) | 5 | 32 | even | 32 × 32 = 1024 |
On the way down the exponent takes the values 10, 5, 2, 1 and 0. fastPow(2, 0) returns 1. Table 12.8 shows the way back. Exponent 1 is odd: 1 × 1 × 2 = 2. Exponent 2 is even: 2 × 2 = 4. Exponent 5 is odd: 4 × 4 × 2 = 32. Exponent 10 is even: 32 × 32 = 1024. In total 5 calls were made; the plain method would have made 11.
The number of calls depends on the number of binary digits of the exponent. For an exponent of 1 or more, the number of calls is ⌊log₂ exp⌋ + 2. Measurements from the version with a counter agree with this formula:
| Exponent | Plain power: calls | fastPow: calls | ⌊log₂ exp⌋ + 2 |
|---|---|---|---|
| 10 | 11 | 5 | 3 + 2 = 5 |
| 16 | 17 | 6 | 4 + 2 = 6 |
| 62 | 63 | 7 | 5 + 2 = 7 |
| 1000 | 1001 | 11 | 9 + 2 = 11 |
| 1.000.000 | 1.000.001 | 21 | 19 + 2 = 21 |
For the millionth power the plain method makes a million calls; with the default stack size this causes a stack overflow. Fast power makes only 21 calls. Time and stack depth are O(log n). The program also computed fastPow(3, 16) = 43,046,721 and fastPow(2, 62) = 4,611,686,018,427,387,904 correctly:
1024
43046721 4611686018427387904The results must fit in a long. 2⁶³ exceeds the range of a long; the call fastPow(2, 63) returns −9,223,372,036,854,775,808 without raising an error. Overflow is a problem independent of the speed of the method.
12.5Divide and conquer
Fast power reduces a problem to one of half the size. The general name for this idea is divide and conquer. The problem is divided into two or more smaller parts. The parts are solved with the same method, that is, by recursion. Then the solutions of the parts are combined to obtain the solution of the original problem. When the parts become small enough they are solved directly; this is the base case.
Divide and conquer is an algorithm design technique that splits a problem into smaller subproblems of the same kind, solves the subproblems recursively, and combines their solutions.
12.5.1Recursive binary search
Binary search looks for a value in a sorted array. It examines the element in the middle of the range. If the target equals the middle element, the search ends. If the middle value is smaller, the target lies in the right half; if it is larger, the target lies in the left half. The half that was not examined is never looked at again. Binary search written with a loop can be written recursively with the same steps. Each call calls itself on half of the range.
static int search(int[] a, int x,
int lo, int hi) {
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (a[mid] == x) return mid;
if (a[mid] < x) return search(a, x, mid + 1, hi);
return search(a, x, lo, mid - 1);
}
// a = {2, 5, 8, 12, 16, 23, 38, 56}
System.out.println(search(a, 38, 0, 7));The range is described by two indices: lo is the lower bound and hi the upper bound. There are two base cases. If lo > hi, the range is empty and the target is not in the array; the method returns −1. If a[mid] == x, the value has been found and its index is returned. The other two lines halve the range. The array itself is not copied; all the calls look at the same array.
In the listing the array is given in a comment line. In the version that was run, the array was defined by the line int[] a = {2, 5, 8, 12, 16, 23, 38, 56};. The second line of the output holds the results of searching for 2, 56 and 20:
6
0 7 -1| Frame | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| search(a, 38, 0, 7) | 0 | 7 | 3 | 12 | 12 < 38: right half, search(a, 38, 4, 7) |
| search(a, 38, 4, 7) | 4 | 7 | 5 | 23 | 23 < 38: right half, search(a, 38, 6, 7) |
| search(a, 38, 6, 7) | 6 | 7 | 6 | 38 | 38 == 38: return 6 |
According to Table 12.10, 38 is found in three calls. In the first call mid = 0 + (7 − 0) / 2 = 3 and a[3] = 12. Since 12 < 38, the search continues in the right half. In the second call mid = 5 and a[5] = 23; the search again moves right. In the third call mid = 6 and a[6] = 38: the value has been found. The 6 passes through two frames and reaches main.
When a value that is not in the array is searched for, the range eventually becomes empty. Table 12.11 shows the search for 20. In the fourth call lo = 5 and hi = 4; 5 > 4 is true and −1 is returned.
| Frame | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| search(a, 20, 0, 7) | 0 | 7 | 3 | 12 | 12 < 20: right half, search(a, 20, 4, 7) |
| search(a, 20, 4, 7) | 4 | 7 | 5 | 23 | 23 > 20: left half, search(a, 20, 4, 4) |
| search(a, 20, 4, 4) | 4 | 4 | 4 | 16 | 16 < 20: right half, search(a, 20, 5, 4) |
| search(a, 20, 5, 4) | 5 | 4 | — | — | 5 > 4: return −1 |
Because the range is halved on every call, an array of n elements needs at most about log₂ n + 1 calls. For an array of 8 elements the worst case is 4 calls: the searches for 56 and 20 took 4 calls. The time is O(log n). The extra stack memory of the recursive version is also O(log n); the loop version does the same job with O(1) extra memory.
Forgetting to write return in front of a recursive call. In the line if (a[mid] < x) search(a, x, mid + 1, hi); the subcall finds the value but the value is not used. The method continues to the lines below and returns a wrong result. In a recursive method that returns a value, the result of the subcall must either be returned or used in a computation.
12.5.2Merge sort
Merge sort is a typical example of divide and conquer. The array is split in the middle. Each half is sorted recursively. Then the two sorted halves are merged into a single sorted array. An array with one element is already sorted; this is the base case.
static void mergeSort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int mid = (lo + hi) / 2;
mergeSort(a, lo, mid);
mergeSort(a, mid + 1, hi);
int[] t = new int[hi - lo + 1];
int i = lo, j = mid + 1, k = 0;
while (i <= mid && j <= hi)
t[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i <= mid) t[k++] = a[i++];
while (j <= hi) t[k++] = a[j++];
System.arraycopy(t, 0, a, lo, t.length);
}The method has three parts:
- Base case: if
lo >= hi, the range has at most one element and the method returns at once. - Split:
midis computed;mergeSort(a, lo, mid)sorts the left half andmergeSort(a, mid + 1, hi)sorts the right half. - Merge: a temporary array named
tis created.iadvances through the left half andjthrough the right half. At each step the smaller of the two front elements is written to t. When one half runs out, the rest of the other is appended as it is. FinallySystem.arraycopycopies t back into the corresponding region of the array.
The “less than or equal” in the comparison a[i] <= a[j] is a deliberate choice. For equal elements, the one on the left is written first, so the original order of equal values is preserved. This property is called stability, and merge sort is a stable sorting method.
| Call no. | Frame | Work done | Array |
|---|---|---|---|
| 1 | mergeSort(a, 0, 3) | mid = 1: [0..1] and [2..3] to be sorted | [5, 2, 4, 1] |
| 2 | mergeSort(a, 0, 1) | mid = 0: [0..0] and [1..1] to be sorted | [5, 2, 4, 1] |
| 3 | mergeSort(a, 0, 0) | single element: returns at once | [5, 2, 4, 1] |
| 4 | mergeSort(a, 1, 1) | single element: returns at once | [5, 2, 4, 1] |
| 2 | mergeSort(a, 0, 1) | merge: [2, 5] | [2, 5, 4, 1] |
| 5 | mergeSort(a, 2, 3) | mid = 2: [2..2] and [3..3] to be sorted | [2, 5, 4, 1] |
| 6 | mergeSort(a, 2, 2) | single element: returns at once | [2, 5, 4, 1] |
| 7 | mergeSort(a, 3, 3) | single element: returns at once | [2, 5, 4, 1] |
| 5 | mergeSort(a, 2, 3) | merge: [1, 4] | [2, 5, 1, 4] |
| 1 | mergeSort(a, 0, 3) | merge: [1, 2, 4, 5] | [1, 2, 4, 5] |
Table 12.12 gives the true order of the calls. Call 1 splits the array into [0..1] and [2..3]. The right half is not started until the left half is completely finished. Call 2 splits [5, 2] into two single elements, both return at once, and then the merge produces [2, 5]. The array is now [2, 5, 4, 1]. The right half turns into [1, 4] in the same way. Finally, call 1 merges [2, 5] with [1, 4]. The comparisons are between 2 and 1, 2 and 4, and 5 and 4; when the right half runs out, 5 is appended. The result is [1, 2, 4, 5].
The program also sorted an array of 7 elements:
[1, 2, 4, 5]
[3, 9, 10, 27, 38, 43, 82]The cost is computed as follows. During splitting, the size of the array halves at each level. An array of n elements is broken into single elements in about log₂ n levels. Merging all the pieces at each level requires writing n elements in total. The total work is the number of levels times the work per level: O(n log n). Because a temporary array is used for merging, the extra memory is O(n). The stack depth, however, is only O(log n). For a reverse-sorted array of 1024 elements, the version with a counter counted 2047 calls, a maximum depth of 11 frames and 5120 comparisons. 5120 = 512 × 10, that is, (n/2) · log₂ n.
For comparison: methods with two nested loops, such as selection sort or bubble sort, make about n²/2 comparisons. For 1024 elements that means roughly 520 thousand comparisons. Merge sort sorts the same array with a hundred times fewer comparisons.
12.6Recursion with two calls
In most of the examples so far, each call made at most one new call. Merge sort makes two calls: one for the left half and one for the right half. In methods where every call makes two calls, the calls form a tree rather than a chain. This tree is called a recursion tree. The root of the tree is the first call, and the children of each node are the subcalls that call makes. The Towers of Hanoi and subset generation are two classic examples of this structure.
12.6.1Towers of Hanoi
The Towers of Hanoi is a puzzle. There are three pegs: A, B and C. Peg A holds n disks arranged from largest to smallest. The goal is to move all the disks to peg C. There are two rules: only one disk may be moved at a time, and it must be the top disk of a peg. A larger disk may never be placed on a smaller one.
The puzzle looks hard at first, but its recursive solution takes three lines. To move n disks from A to C, first the top n − 1 disks are moved to B, with C serving as the spare peg. Then the largest disk, left alone on A, is moved to C. Finally the n − 1 disks on B are moved to C, with A as the spare. Moving n − 1 disks is a smaller instance of the same problem. If there are no disks, there is nothing to do.
static void hanoi(int n, char from,
char to, char via) {
if (n == 0) return;
hanoi(n - 1, from, via, to);
System.out.print(from + "->" + to + " ");
hanoi(n - 1, via, to, from);
}
hanoi(3, 'A', 'C', 'B');A->C A->B C->B A->C B->A B->C A->C The method has four parameters: the number of disks, the source peg, the target peg and the helper (via) peg. In the first recursive call, to and via swap places: n − 1 disks go to the via peg. In the second call, from and via swap places: n − 1 disks go from the via peg to the target. The print statement sits between the two calls, so a move is printed only after the left subtree has finished completely.
| Move | Disk | Transfer | Frame that makes the move |
|---|---|---|---|
| 1 | 1 | A → C | hanoi(1, A, C, B) |
| 2 | 2 | A → B | hanoi(2, A, B, C) |
| 3 | 1 | C → B | hanoi(1, C, B, A) |
| 4 | 3 | A → C | hanoi(3, A, C, B) |
| 5 | 1 | B → A | hanoi(1, B, A, C) |
| 6 | 2 | B → C | hanoi(2, B, C, A) |
| 7 | 1 | A → C | hanoi(1, A, C, B) |
Table 12.13 shows the seven moves and which call makes each one. Disk 1 is the smallest and disk 3 the largest. The first three moves carry the top two disks to B. Move 4 takes the largest disk to C; this move is made by the outermost call, hanoi(3, A, C, B). The last three moves carry the two disks on B to C. Disk 1 moves on every other move: moves 1, 3, 5 and 7 are its. Figure 12.15 shows four moments.
The number of moves can also be found recursively. Let h(n) be the number of moves needed to move n disks. The solution moves n − 1 disks twice and moves the largest disk once: h(n) = 2·h(n − 1) + 1, h(0) = 0. From this, h(1) = 1, h(2) = 3, h(3) = 7, h(4) = 15 and h(5) = 31. The general formula is h(n) = 2ⁿ − 1. The formula is verified by induction: 2·(2ⁿ⁻¹ − 1) + 1 = 2ⁿ − 1.
| Number of disks n | Move | 2ⁿ − 1 | Calls | Maximum depth |
|---|---|---|---|---|
| 1 | 1 | 1 | 3 | 2 |
| 2 | 3 | 3 | 7 | 3 |
| 3 | 7 | 7 | 15 | 4 |
| 4 | 15 | 15 | 31 | 5 |
| 5 | 31 | 31 | 63 | 6 |
| 10 | 1023 | 1023 | 2047 | 11 |
| 20 | 1.048.575 | 1.048.575 | 2.097.151 | 21 |
Table 12.14 shows two different kinds of growth. The number of moves and calls is exponential: it roughly doubles with each added disk. The stack depth is linear: n + 1. This solution of Hanoi is optimal. It is impossible to move n disks in fewer than 2ⁿ − 1 moves, because for the largest disk to move once, the n − 1 disks on top of it must be moved away completely twice. The exponential growth is a property of the problem itself, not of the algorithm. For 64 disks the number of moves needed is 2⁶⁴ − 1 ≈ 1.8 × 10¹⁹.
12.6.2Generating subsets and backtracking
The set {1, 2} has four subsets: {1, 2}, {1}, {2} and the empty set. A set of n elements has 2ⁿ subsets. The reason is simple: for each element there are two choices, either it is included in the subset or it is not. For n elements the choices multiply: 2 × 2 × … × 2 = 2ⁿ.
This idea of “two choices for each element” becomes a recursive method. The method decides about the i-th element. First it adds the element to the list and calls itself for the remaining elements. Then it removes the element from the list and calls itself again for the remaining elements. If a decision has been made for all the elements, the list is a subset and it is printed.
static void subsets(int[] a, int i,
List<Integer> chosen) {
if (i == a.length) {
System.out.println(chosen);
return;
}
chosen.add(a[i]);
subsets(a, i + 1, chosen);
chosen.remove(chosen.size() - 1);
subsets(a, i + 1, chosen);
}
subsets(new int[]{1, 2}, 0, new ArrayList<>());chosen is a list that holds the elements selected so far (List<Integer>). All the frames share the same list object; each call receives the list itself, not a copy. chosen.add(a[i]) appends the element at the end. chosen.remove(chosen.size() - 1) removes the last element and returns the list to its state before the addition. Without this removal step, the second call would find the element added by the first call still in the list.
Backtracking is a search technique that makes choices step by step, explores the consequences of a choice recursively, and then undoes that choice and tries the next option.
| Step | Frame | Work | chosen | Output |
|---|---|---|---|---|
| 1 | subsets(i=0) | 1 included: chosen.add(1) | [1] | |
| 2 | subsets(i=1) | 2 included: chosen.add(2) | [1, 2] | |
| 3 | subsets(i=2) | base case: print | [1, 2] | [1, 2] |
| 4 | subsets(i=1) | 2 excluded: chosen.remove(...) | [1] | [1, 2] |
| 5 | subsets(i=2) | base case: print | [1] | [1, 2] [1] |
| 6 | subsets(i=0) | 1 excluded: chosen.remove(...) | [] | [1, 2] [1] |
| 7 | subsets(i=1) | 2 included: chosen.add(2) | [2] | [1, 2] [1] |
| 8 | subsets(i=2) | base case: print | [2] | [1, 2] [1] [2] |
| 9 | subsets(i=1) | 2 excluded: chosen.remove(...) | [] | [1, 2] [1] [2] |
| 10 | subsets(i=2) | base case: print | [] | [1, 2] [1] [2] [] |
Table 12.15 shows in ten steps how the four subsets are generated. In steps 1 and 2 both elements are added and the list becomes [1, 2]. In step 3, i = 2, so the end of the array has been reached: [1, 2] is printed. In step 4 the method backs up and 2 is removed. The list becomes [1], and the “2 excluded” branch prints [1]. In step 6 control returns to the frame with i = 0 and 1 is removed as well. After that, the “1 excluded” branches produce the subsets [2] and [].
The output of the program contains first the subsets of the two-element set and, after the “--” line, the subsets of {1, 2, 3}:
[1, 2]
[1]
[2]
[]
--
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
[]The output order is the left-to-right traversal order of the recursion tree. At each level the “included” branch runs first, then the “excluded” branch. This is why the first line is the set containing all the elements and the last line is the empty set.
Each level of the recursion tree corresponds to one element. For an array of n elements the tree has 2ⁿ leaves and 2ⁿ⁺¹ − 1 nodes in total. The version with a counter counted 7 calls for n = 2, 15 for n = 3 and 2047 for n = 10. The stack depth is only n + 1. The time is O(2ⁿ), but this is the price that any method that wants to produce all 2ⁿ subsets must pay.
12.7The call stack and stack overflow
12.7.1What does a stack frame hold?
All the earlier examples used the call stack. This section explains exactly what is stored on the stack and why the stack is limited. When a method calls another method, the work of the calling method is left half finished and will continue later from where it stopped. Three pieces of information must be saved for this:
- Parameters: the values passed to the call. In the factorial(3) frame, n = 3.
- Local variables: variables defined inside the method.
halfin fastPow, ormid,iandjin mergeSort, are such variables. - Return point: the instruction in the calling method at which to continue when the called method finishes. When factorial(3) finishes, execution returns to the multiplication in the frame of factorial(4).
The Java Virtual Machine (JVM) keeps this information in a separate stack frame for each call. The frames sit on top of one another in the stack memory reserved for the thread. When a new call is made, a frame is added on top. When a method ends with return, the top frame is removed and control passes to the frame below. Frames therefore close in reverse order: the last one opened closes first.
Stack memory is limited. In Java, the stack of each thread has a fixed size set when the program starts. On 64-bit systems this default size is usually 1 MB. If the frames pile up past the limit, the JVM cannot find room for a new frame and throws an error. This situation is called stack overflow.
Stack overflow occurs when the frames on the call stack fill the memory set aside for the stack. In Java, stack overflow is reported with a java.lang.StackOverflowError. Recursion that never reaches the base case is called infinite recursion; infinite recursion always ends in a stack overflow.
Stack overflow has two causes. The first is infinite recursion: there is no base case, it is written wrongly, or the problem does not shrink. The second is recursion that is written correctly but goes very deep. The base case will be reached, but the frames accumulated by then do not fit on the stack. Linear recursion opens as many frames as the size of the input, so even a correct method can overflow on large inputs.
12.7.2StackOverflowError
The shortest example in the presentation is a method that contains no condition at all:
static void forever(int n) {
forever(n + 1);
}
forever(0);The call forever(0) immediately calls forever(1), which calls forever(2), and so on. Since no call ever returns, no frame is ever removed. Figure 12.18 shows this accumulation. When the stack is full, the JVM throws a StackOverflowError. Because the error is not caught, the program ends and the error text is written to the standard error stream (stderr). The first lines of the error text of the program run on JDK 21 are:
Exception in thread "main" java.lang.StackOverflowError
at S19.forever(S19.java:5)
at S19.forever(S19.java:5)
at S19.forever(S19.java:5)
...Each “at” line shows one frame on the stack: it gives the class and method and the line of the source file. The line number is 5 because in the program the method forever makes its call on line 5 of the class. These lines repeat thousands of times. By default the JVM writes at most 1024 frames into the error text; the error text of the program that was run also consisted of 1 header line and 1024 “at” lines. When the same line repeats again and again in such an error text, it is a clear sign of infinite or very deep recursion.
The number of calls after which the overflow occurs is not fixed. The size of a frame depends on the number of parameters and local variables of the method. Whether the JVM runs the code by interpreting it or by compiling it to machine code also changes the frame size. The program below counts the calls made up to the moment of overflow. Because the error is caught with catch, the program does not end and can print the count:
// Counts how many calls it takes to get a StackOverflowError at the default stack size (varies with the JVM and conditions).
public class Depth {
static int count;
static void forever(int n) {
count++;
forever(n + 1);
}
static long power(long base, int n) {
count++;
if (n == 0) return 1;
return base * power(base, n - 1);
}
static int sum(int n) {
if (n <= 0) return 0;
return n + sum(n - 1);
}
public static void main(String[] args) {
for (int k = 0; k < 3; k++) {
count = 0;
try {
forever(0);
} catch (StackOverflowError e) {
System.out.println("forever: " + count + " calls until " + e.getClass().getName());
}
}
count = 0;
try {
power(2, -1);
} catch (StackOverflowError e) {
System.out.println("power(2, -1): " + count + " calls until " + e.getClass().getSimpleName());
}
for (int n : new int[]{1000, 5000, 10000, 100000, 1000000}) {
try {
System.out.println("sum(" + n + ") = " + sum(n));
} catch (StackOverflowError e) {
System.out.println("sum(" + n + "): StackOverflowError");
}
}
}
}The output of one run of the program is:
forever: 23539 calls until java.lang.StackOverflowError
forever: 62252 calls until java.lang.StackOverflowError
forever: 62252 calls until java.lang.StackOverflowError
power(2, -1): 8079 calls until StackOverflowError
sum(1000) = 500500
sum(5000) = 12502500
sum(10000) = 50005000
sum(100000): StackOverflowError
sum(1000000): StackOverflowErrorWhen the same method was tried three times in the same program, it overflowed after about 23 thousand calls on the first attempt and after about 62 thousand on the later ones. When the program was run several more times, the count of the first attempt varied between 22 thousand and 27 thousand. The numbers may come out slightly different on each run, but the order of magnitude is clear: a few tens of thousands of calls at the default stack size. sum(10,000) works, while sum(100,000) overflows. The stack size can be increased with an option such as java -Xss4m Program. This only pushes the limit further away; it does not solve the problem of deep recursion.
Catching StackOverflowError with catch and trying to carry on with the program. This error is a symptom of a programming mistake or of a badly chosen algorithm. The program above catches the error only to take measurements. In a real program the fix is to correct the base case, to check the input, or to turn deep recursion into a loop.
12.8Recursion or a loop?
12.8.1Criteria for choosing
Every method written with recursion can also be written with a loop, and every method written with a loop can also be written with recursion. The choice between the two depends not on which one is more “powerful” but on the structure of the problem and on cost.
Recursion is the natural choice for problems that resemble themselves. Tree-shaped data, directory and folder structures, divide-and-conquer algorithms and backtracking are of this kind. For these problems the recursive code is very close to the mathematical definition and easy to read. It is possible to write Hanoi and subset generation with a loop, but then you have to manage by hand a stack data structure that does the job of the call stack.
For simple linear repetition, on the other hand, the loop is better. Factorial, the sum from 1 to n and the digit sum are written just as clearly with a loop. A loop runs in a single frame and does not open a new frame for each iteration. Its extra stack memory is O(1), and no matter how large the input, the stack does not overflow. Making a call also has a small time cost: opening and closing a frame is more expensive than one iteration of a loop.
The choice should not be made by looking only at how short the code is. Three criteria are weighed together: correctness, readability and resource use. A recursive solution with a clear base case and a clear shrinking step can reduce the chance of mistakes. But if the size of the input can exceed tens of thousands, linear recursion puts the stack at risk. A recursion that solves the same subproblem many times puts the time at risk; this is seen in detail in the Fibonacci example.
| Property | Recursive | Loop |
|---|---|---|
| Time complexity | O(n) | O(n) |
| Extra stack memory | O(n): n frames | O(1): a single frame |
| Flow | Close to the mathematical definition | Explicit counter and accumulator |
| Risk of depth | Yes: the stack can overflow for large n | None |
12.8.2Factorial with a loop
The loop version of factorial works with an accumulator. result starts at 1 and is multiplied by the counter i on every iteration:
static long factorialLoop(int n) {
long result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
System.out.println(factorialLoop(4));24| Iteration | i | i <= n | result (after the body) |
|---|---|---|---|
| 1 | 2 | true | 2 |
| 2 | 3 | true | 6 |
| 3 | 4 | true | 24 |
| — | 5 | false | 24 (loop ends) |
Table 12.17 shows three iterations. At i = 2 result is 2, at i = 3 it is 6, and at i = 4 it is 24. At i = 5, 5 ≤ 4 is false and the loop ends. Starting the loop at i = 2 is deliberate: multiplying by 1 does not change the result. For n = 0 and n = 1 the loop never runs and 1 is returned, which agrees with the definition 0! = 1! = 1.
Compared with the recursive version, the computation is the same: 2 × 3 × 4 = 24. The difference lies in the order of the multiplications and in stack use. In the loop version the multiplications are done going forward, from small to large. In the recursive version the calls open from large to small and the multiplications are done on the way back. In the loop version the stack never exceeds 2 frames. A while version of the same method does the same job at the same cost; its results for n = 0 to 5 are 1, 1, 2, 6, 24 and 120.
12.9Fibonacci and memoization
12.9.1Direct Fibonacci
The Fibonacci sequence starts with 0 and 1. Each following term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, … The definition is recursive: fib(0) = 0, fib(1) = 1 and fib(n) = fib(n − 1) + fib(n − 2). The method translated directly into Java is:
static long fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
System.out.println(fib(4));3The method is a word-for-word rendering of the definition and gives the correct result. But it differs from factorial in one important way: in the recursive case two calls are made. First fib(n − 1) is computed completely, then fib(n − 2). The calls form a tree, not a chain.
| Call no. | Frame | Depth | Explanation |
|---|---|---|---|
| 1 | fib(4) | 1 | waits for fib(3) + fib(2) |
| 2 | fib(3) | 2 | waits for fib(2) + fib(1) |
| 3 | fib(2) | 3 | waits for fib(1) + fib(0) |
| 4 | fib(1) | 4 | base case: return 1 |
| 5 | fib(0) | 4 | base case: return 0 |
| fib(2) returns | 3 | 1 + 0 = 1 | |
| 6 | fib(1) | 3 | base case: return 1 |
| fib(3) returns | 2 | 1 + 1 = 2 | |
| 7 | fib(2) | 2 | waits for fib(1) + fib(0) |
| 8 | fib(1) | 3 | base case: return 1 |
| 9 | fib(0) | 3 | base case: return 0 |
| fib(2) returns | 2 | 1 + 0 = 1 | |
| fib(4) returns | 1 | 2 + 1 = 3 |
Table 12.18 gives the order of the nine calls. fib(4) calls fib(3), fib(3) calls fib(2), and fib(2) calls fib(1). fib(1) and fib(0) are base cases. fib(2) = 1 + 0 = 1 is computed. For its right term, fib(3) calls fib(1) and finds 1 + 1 = 2. Then fib(4) calls fib(2) for its right term. This call, number 7, redoes exactly the work done by call number 3. fib(2) is computed twice, fib(1) three times and fib(0) twice. Although the result is 3, 9 calls were made. The stack depth is at most 4, however: at any moment only the frames along one path from the root to a leaf are open.
As n grows, the repetition increases quickly. Figure 12.22 shows the tree for fib(5). 15 calls are made: f(3) is computed 2 times, f(2) 3 times, f(1) 5 times and f(0) 3 times. The f(3) subtree in the right half of the tree is already contained in the f(4) subtree in the left half. The subtrees of fib(n − 1) and fib(n − 2) overlap to a large extent.
12.9.2How the call count grows
The call count is found most reliably by counting. In the program below, a counter has been added to the method. Every call increases the counter by 1:
public class FibCounter {
static long calls = 0;
static long fib(int n) {
calls++;
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
for (int n : new int[]{5, 10, 20, 30}) {
calls = 0;
long result = fib(n);
System.out.println("fib(" + n + ") = " + result + ", calls = " + calls);
}
}
}fib(5) = 5, calls = 15
fib(10) = 55, calls = 177
fib(20) = 6765, calls = 21891
fib(30) = 832040, calls = 2692537The numbers can also be found with a formula. Let c(n) be the number of calls made for fib(n). The first call counts as 1; the calls of the two subtrees are added to it: c(n) = 1 + c(n − 1) + c(n − 2), c(0) = c(1) = 1. From this, c(2) = 3, c(3) = 5, c(4) = 9, c(5) = 15 and c(6) = 25. The solution of this recurrence is c(n) = 2·fib(n + 1) − 1. For example, since fib(11) = 89, c(10) = 177.
| n | fib(n) | Recursive: number of calls | Loop: number of iterations |
|---|---|---|---|
| 5 | 5 | 15 | 5 |
| 10 | 55 | 177 | 10 |
| 20 | 6765 | 21.891 | 20 |
| 30 | 832.040 | 2.692.537 | 30 |
| 40 | 102.334.155 | 331.160.281 | 40 |
Table 12.19 puts the two kinds of growth side by side. The loop version runs n iterations; its work is proportional to n. The call count of the recursive version, however, is multiplied by about 123 each time n grows by 10. The reason is the Fibonacci numbers themselves. The ratio of two consecutive Fibonacci numbers approaches about 1.618. This number is called the golden ratio and is written φ. φ¹⁰ ≈ 123. Since the call count is proportional to fib(n + 1), it also grows by a factor of about 1.618 at each step. The time is O(φⁿ). The O(2ⁿ) notation used in the slides is a rough upper bound on this: every call makes at most two calls and the depth of the tree is n. Whichever is used, the growth is exponential.
The practical meaning of exponential growth is this: for fib(40), 331 million calls are made. For fib(50) the number exceeds 40 billion. The loop version finds fib(50) in 50 iterations. Stack depth is not a problem in either version: the recursive version opens at most n frames. The problem is time.
Believing that every recursive method that matches the definition exactly is efficient. The direct Fibonacci method is correct but solves the same subproblems again and again. If several nodes with the same argument appear in the recursion tree, the method is doing unnecessary work. This repetition is removed by saving the results, or by computing from small to large with a loop.
12.9.3Memoization
The cure for repetition is simple: when the result of a subproblem is computed for the first time, it is written down somewhere. When the same subproblem is requested again, no computation is done; the recorded value is returned. This technique is called memoization.
Memoization is the technique in which a recursive method stores the subproblem results it has computed in an array or table and, when the same input comes again, returns the recorded value without expanding the recursion tree again.
For Fibonacci, the place to record results is a long array. memo[k] holds the result of fib(k). In Java, all the cells of a new numeric array start at 0. Since fib(k) ≥ 1 for k ≥ 1, the value 0 can be used to mean “not computed yet”.
static long fib(int n, long[] memo) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
memo[n] = fib(n - 1, memo)
+ fib(n - 2, memo);
return memo[n];
}
long[] memo = new long[6];
System.out.println(fib(5, memo));5The method differs from the plain version in only three places:
- It takes the array as a parameter. All the calls share the same array object; the values written by one call are seen by the others.
- After the base case it looks at the record: if
memo[n] != 0, the result is already known and is returned at once. - It saves the result before returning it:
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);.
The call count of the memoized version was also measured with a counter:
public class MemoCounter {
static long calls = 0;
static long fib(int n, long[] memo) {
calls++;
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
memo[n] = fib(n - 1, memo)
+ fib(n - 2, memo);
return memo[n];
}
public static void main(String[] args) {
for (int n : new int[]{5, 10, 20, 30, 50}) {
calls = 0;
long result = fib(n, new long[n + 1]);
System.out.println("fib(" + n + ") = " + result + ", calls = " + calls);
}
}
}fib(5) = 5, calls = 9
fib(10) = 55, calls = 19
fib(20) = 6765, calls = 39
fib(30) = 832040, calls = 59
fib(50) = 12586269025, calls = 99For n of 1 or more, the call count is 2n − 1. The reason is this: each of fib(n − 1), …, fib(2) is computed once and makes two calls. There are n − 1 of them; adding the first call gives 1 + 2(n − 1) = 2n − 1. For fib(30) the call count drops from 2,692,537 to 59. The time becomes O(n). In exchange, an array of n + 1 cells is used: the extra memory is O(n). Memory has been spent to gain time.
12.9.4Tracing memoized fib(5)
| Call no. | Frame | Work | memo |
|---|---|---|---|
| 1 | fib(5) | memo[5] == 0: to be computed | [0, 0, 0, 0, 0, 0] |
| 2 | fib(4) | memo[4] == 0: to be computed | [0, 0, 0, 0, 0, 0] |
| 3 | fib(3) | memo[3] == 0: to be computed | [0, 0, 0, 0, 0, 0] |
| 4 | fib(2) | memo[2] == 0: to be computed | [0, 0, 0, 0, 0, 0] |
| 5 | fib(1) | base case: return 1 | [0, 0, 0, 0, 0, 0] |
| 6 | fib(0) | base case: return 0 | [0, 0, 0, 0, 0, 0] |
| fib(2) returns | memo[2] = 1 saved | [0, 0, 1, 0, 0, 0] | |
| 7 | fib(1) | base case: return 1 | [0, 0, 1, 0, 0, 0] |
| fib(3) returns | memo[3] = 2 saved | [0, 0, 1, 2, 0, 0] | |
| 8 | fib(2) | memo[2] = 1: from memo, return 1 | [0, 0, 1, 2, 0, 0] |
| fib(4) returns | memo[4] = 3 saved | [0, 0, 1, 2, 3, 0] | |
| 9 | fib(3) | memo[3] = 2: from memo, return 2 | [0, 0, 1, 2, 3, 0] |
| fib(5) returns | memo[5] = 5 saved | [0, 0, 1, 2, 3, 5] |
Table 12.20 shows the nine calls and the memo filling up. The first four calls are fib(5), fib(4), fib(3) and fib(2). None of them is in the memo, and all call their left terms in order to be computed. fib(1) and fib(0) are base cases. fib(2) = 1 + 0 = 1 is computed and written to memo[2]. fib(3) calls fib(1) for its right term and finds 2; memo[3] becomes 2.
The effect of memoization shows in call 8. fib(4) calls fib(2) for its right term. In the plain version this call would open a new subtree. Here memo[2] = 1, and the value returns at once. In call 9, the fib(3) that fib(5) asks for also comes from the memo. In the end the memo array is [0, 0, 1, 2, 3, 5] and 5 is printed. memo[0] and memo[1] are never used, because 0 and 1 are base cases.
Another version keeps the array as a static field instead of a parameter: static long[] memo = new long[50];. In this form the array is created once for the whole program, and later fib calls also use the earlier computations. An array of 50 cells is enough up to fib(49); fib(49) = 7,778,742,049 does not fit in an int but does fit in a long.
12.9.5Combinations with memoization
Memoization is not specific to Fibonacci. It works in any recursion whose subproblems overlap. One of the exercises in the slides is the number of combinations. The number of ways to choose k items from n is written C(n, k) and satisfies the rule of Pascal's triangle: C(n, k) = C(n − 1, k − 1) + C(n − 1, k). The rule is explained like this: a particular item is either chosen (k − 1 are chosen from the remaining n − 1 items) or not chosen (k are chosen from the remaining n − 1 items). The base cases are C(n, 0) = 1 and C(n, n) = 1: there is one way to choose no items and one way to choose all of them.
The program below computes the combination count in plain and memoized form and compares the call counts of the two versions. The memoized version uses a two-dimensional long array; memo[n][k] holds the result for C(n, k).
// Exercise from the slides: choose(n, k) = choose(n - 1, k - 1) + choose(n - 1, k)
public class Combinations {
static long calls;
static long choose(int n, int k) {
calls++;
if (k == 0 || k == n) return 1;
return choose(n - 1, k - 1) + choose(n - 1, k);
}
static long chooseMemo(int n, int k, long[][] memo) {
calls++;
if (k == 0 || k == n) return 1;
if (memo[n][k] != 0) return memo[n][k];
memo[n][k] = chooseMemo(n - 1, k - 1, memo) + chooseMemo(n - 1, k, memo);
return memo[n][k];
}
public static void main(String[] args) {
int[][] g = {{4, 2}, {5, 2}, {10, 5}, {20, 10}, {30, 15}};
for (int[] x : g) {
calls = 0;
long v = choose(x[0], x[1]);
long c1 = calls;
calls = 0;
long w = chooseMemo(x[0], x[1], new long[x[0] + 1][x[1] + 1]);
System.out.println("C(" + x[0] + ", " + x[1] + ") = " + v + " / " + w + ": plain " + c1 + " calls, memoized " + calls + " calls");
}
}
}C(4, 2) = 6 / 6: plain 11 calls, memoized 9 calls
C(5, 2) = 10 / 10: plain 19 calls, memoized 13 calls
C(10, 5) = 252 / 252: plain 503 calls, memoized 51 calls
C(20, 10) = 184756 / 184756: plain 369511 calls, memoized 201 calls
C(30, 15) = 155117520 / 155117520: plain 310235039 calls, memoized 451 callsThe two versions give the same result: C(5, 2) = 10 and C(30, 15) = 155,117,520. The call count of the plain version is 2·C(n, k) − 1, because the result is built by adding up the 1s at the leaves of the tree. For C(30, 15) this means more than 310 million calls. The memoized version computes each (n, k) pair once and finds the same result in 451 calls.
12.10Tail recursion
12.10.1The accumulator parameter
In recursive factorial, each frame leaves one job for the way back: multiplying the subresult by n. That is why the frame has to wait. The same computation can also be written so that the multiplication is done before the call. For this, the intermediate result is carried in a second parameter. This parameter is called the accumulator.
static long fact(int n, long acc) {
if (n <= 1) return acc;
return fact(n - 1, n * acc);
}
// fact(4, 1) → fact(3, 4)
// → fact(2, 12) → fact(1, 24) → 24fact(n, acc) computes the value n! × acc. In the first call, acc is given as 1: fact(4, 1) = 4!. In the recursive case the multiplication is done inside the call, while the argument is being computed: n * acc. When the call returns, no work remains; the result of the subcall is returned as it is. In the base case, acc carries the whole of the sought result.
Tail recursion is recursion in which the recursive call is the last operation of the method. After the call returns, no computation remains in the frame; the result of the subcall is returned unchanged.
Since no work remains on the way back, there is no need to keep the old frame. Some languages and compilers recognize this situation. Instead of opening a new frame, they reuse the old one with the new arguments. This transformation is called tail call optimization. When the optimization is applied, tail recursion uses as little memory as a loop: O(1). The standard of languages such as Scheme requires it.
Java, however, does not guarantee this optimization. The Java compiler and the JDK 21 virtual machine do not turn tail calls into loops. Every call still opens a new frame. For this reason tail recursion does not give stack safety in Java: fact(100,000, 1) overflows just like any deep linear recursion. If you need deep tail recursion in Java, turning it into a loop is the programmer's job. The translation is easy: the parameters become loop variables, and the recursive call becomes an update of those variables.
12.10.2Tracing fact(4, 1)
static long fact(int n, long acc) {
if (n <= 1) return acc;
return fact(n - 1, n * acc);
}
System.out.println(fact(4, 1)); // 24The program prints 24. The version that was run also printed the results of fact(20, 1), fact(1, 1) and fact(0, 1):
24
2432902008176640000 1 1| Frame | n | acc | Work done before the call | Next step |
|---|---|---|---|---|
| fact(4, 1) | 4 | 1 | 4 × 1 = 4 | fact(3, 4) |
| fact(3, 4) | 3 | 4 | 3 × 4 = 12 | fact(2, 12) |
| fact(2, 12) | 2 | 12 | 2 × 12 = 24 | fact(1, 24) |
| fact(1, 24) | 1 | 24 | 1 <= 1 → true | return 24 |
Table 12.21 gives the chain: fact(4, 1) → fact(3, 4) → fact(2, 12) → fact(1, 24) → 24. The multiplications are 4 × 1 = 4, 3 × 4 = 12 and 2 × 12 = 24, and all of them are done on the way down. In ordinary factorial the multiplications were done on the way back in the order 2, 6, 24. Here the order of multiplication is 4, 12, 24, and on the way back only 24 is carried.
Figure 12.26 shows the real situation in Java. The old frames have nothing left to wait for, but they stay on the stack. At the deepest moment there are 5 frames including main; this is the same as for ordinary factorial(4). Tail recursion does not reduce memory in Java; the extra memory is still O(n). The benefit of the technique shows up in other languages. In Java it can be thought of as an intermediate step toward turning the recursion into a loop.
Starting the accumulator wrongly in the first call. In a method that accumulates a product, the accumulator starts at 1; in one that accumulates a sum, it starts at 0. The call fact(4, 0) returns 0, because it multiplies by 0 at every step. To prevent this mistake a one-parameter wrapper method is usually written: static long factorial(int n) { return fact(n, 1); }. Only this method is called from outside.
12.11Overflow, edge cases and debugging
12.11.1long overflow
Stack overflow and integer overflow are different things. In stack overflow, the calls do not fit in memory. In integer overflow, the computed number exceeds the largest value the type can hold. Factorial reaches this second kind very quickly. A long holds at most 9,223,372,036,854,775,807. 20! = 2,432,902,008,176,640,000 is below this limit. 21! = 51,090,942,171,709,440,000 is about five and a half times the limit.
Java does not throw an exception on integer overflow. The result silently wraps around: the part that exceeds the limit is discarded and the number comes back from the negative side. The program below ran the factorial method from 19 to 22:
public class Overflow {
static long factorial(int n) {
if (n < 0)
throw new IllegalArgumentException();
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
for (int n = 19; n <= 22; n++)
System.out.println("factorial(" + n + ") = " + factorial(n));
System.out.println("Long.MAX_VALUE = " + Long.MAX_VALUE);
System.out.println("21! (BigInteger) = " + java.math.BigInteger.valueOf(21).multiply(new java.math.BigInteger("2432902008176640000")));
System.out.println("fib(92), fib(93) long: " + fib(92) + " " + fib(93));
System.out.println("fastPow(2, 63) = " + fastPow(2, 63) + ", fastPow(2, 64) = " + fastPow(2, 64));
System.out.println("Integer.MIN_VALUE: Math.abs = " + Math.abs(Integer.MIN_VALUE) + ", Math.abs((long) ...) = " + Math.abs((long) Integer.MIN_VALUE));
}
static long fib(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) { long c = a + b; a = b; b = c; }
return a;
}
static long fastPow(long base, int exp) {
if (exp < 0) throw new IllegalArgumentException("exp < 0");
if (exp == 0) return 1;
long half = fastPow(base, exp / 2);
if (exp % 2 == 0) return half * half;
return half * half * base;
}
}factorial(19) = 121645100408832000
factorial(20) = 2432902008176640000
factorial(21) = -4249290049419214848
factorial(22) = -1250660718674968576
Long.MAX_VALUE = 9223372036854775807
21! (BigInteger) = 51090942171709440000
fib(92), fib(93) long: 7540113804746346429 -6246583658587674878
fastPow(2, 63) = -9223372036854775808, fastPow(2, 64) = 0
Integer.MIN_VALUE: Math.abs = -2147483648, Math.abs((long) ...) = 2147483648factorial(21) returns a negative number. Because the program does not crash, the error can go unnoticed. The same problem exists in the other examples. fib(92) fits in a long, fib(93) does not and comes out negative. fastPow(2, 63) gives the smallest long value, and fastPow(2, 64) gives 0. If larger results are needed, the java.math.BigInteger class is used; its numbers can grow as long as memory allows. The 21! value in the program was also computed with BigInteger.
12.11.2Negative exponents and other edge inputs
The call power(2, −1) was discussed in 12.4.1. The base case n == 0 is never satisfied; n goes down through −1, −2, −3, … and the frames pile up. In the Depth program this call ended with a StackOverflowError after about 8 thousand calls. This number is smaller than the one for the forever method. Because the frame size depends on the method's parameters and on how the JVM happens to be running, the overflow point differs from method to method.
There are two remedies. The first is to check the input: if n < 0, an IllegalArgumentException is thrown; the factorial method already does this for negative input. The second is to make negative exponents well defined. The result type is changed to double and a negative exponent is converted to a positive one: 2⁻² = 1 / 2² = 0.25. A common version does this in one line: if (n < 0) return 1.0 / power(b, -n);. The negative branch runs only in the first call; in later calls the exponent is positive.
When testing a recursive method, the following inputs are tried:
- The base case itself: factorial(0), factorial(1), sum(0), the empty string, a one-character string.
- One above the base case: factorial(2), a two-character string. The simplest use of the recursive case is tested here.
- Invalid inputs: a negative n, a negative exponent, a null string. The method must either throw a meaningful exception or return a defined value.
- Large inputs: whether the result fits in the type (factorial(21)) and whether the depth fits on the stack (sum(100,000)).
- Special values: 0 and Integer.MIN_VALUE in digit problems; the first and last elements of the array and a value not in the array when searching.
12.11.3Debugging recursive code
If a recursive method gives a wrong result or never ends, the problem is usually in one of the two parts. Debugging is done in four steps:
- Show that the base case can be reached. For every valid input, the chain of calls must end in the base case. This needs separate checking for jumping reductions (such as n − 2) and for negative inputs.
- Identify the shrinking measure. Something must decrease on every call: n, the length of the string, the size of the range (hi − lo + 1) or the number of remaining elements (a.length − i).
- Put a small input in a table. Write down the moments of call and return together with the depth and the returned values.
- Assess depth and repetition. Does the maximum depth grow with the size of the input or with its logarithm? Is the same argument seen more than once in the recursion tree?
For the third step, temporary print lines can be added to the method. The depth is kept in a counter, and each line is printed indented by the depth. The nesting of the calls then shows in the output. Table 12.22 is such a trace for sum(2).
| Depth | Event | Value |
|---|---|---|
| 0 | sum(2) called | |
| 1 | sum(1) called | |
| 2 | sum(0) called | |
| 2 | sum(0) returned | 0 |
| 1 | sum(1) returned | 1 |
| 0 | sum(2) returned | 3 |
The table shows the opening and closing of a call at the same indentation level. sum(2) opens at depth 0 and closes last. In between, sum(1) and sum(0) open and close. The returned values are 0, 1 and 3. When comparing with the expected value, look for the first call that returns a wrong value. The error is in that call's own lines, because all the subresults it uses are correct.
How deep a method goes and how many calls it makes can also be measured with a version that has counters. All the call counts and depths given in these notes were measured this way. The counter is a static field incremented on entry to the method. For depth, a second field that is incremented on entry and decremented on exit is enough, together with a third field that keeps the largest value seen.
The Recursion Visualizer simulator shows these traces interactively. In the simulator, the calls of factorial, fib, power and hanoi open and close step by step. The call stack and the recursion tree can be followed at the same time. For Fibonacci, memoization can be switched on and off to compare the call counts of the two versions.
12.12Summary
- Recursion is the technique in which a method reduces a problem to a smaller instance of the same problem and calls itself. Every recursive method has two parts: the base case, where the result is known directly, and the recursive case, which shrinks the problem and calls the method itself.
- The problem must shrink measurably on every call and must reach the base case. When the input shrinks in jumps, or for negative inputs, it is safer to write the base case with
<=instead of==. - Each call opens a stack frame that holds its parameters, local variables and return point. Frames close in the reverse of the order in which they were opened. Work placed before the recursive call is done on the way down; work placed after it is done on the way back, in reverse order.
- Linear recursion (factorial, sum, plain power) opens n frames: time and extra stack are O(n). In problems that shrink substantially at every step, such as digit sum, fast power and binary search, the depth is logarithmic.
- Divide and conquer splits a problem into parts, solves the parts recursively and combines them. Merge sort runs in O(n log n) time with O(n) extra memory and a stack depth of O(log n).
- Methods in which each call makes two calls form a recursion tree. The Towers of Hanoi takes 2ⁿ − 1 moves, and subset generation produces 2ⁿ subsets. In these problems the exponential work comes from the problem itself; the stack depth is n + 1.
- Recursion that has no base case, or that goes very deep, fills the stack and ends with a StackOverflowError. On JDK 21 the default stack could carry a few tens of thousands of calls.
- For simple linear repetition, a loop runs in a single frame with O(1) extra stack and does not overflow. For self-similar problems, recursion is close to the definition and readable. The choice is made on correctness, readability and resource use.
- Direct Fibonacci solves the same subproblems again and again. The call count is 2·fib(n + 1) − 1 and grows exponentially: 2,692,537 calls for fib(30).
- Memoization removes the repetition by saving subproblem results. Memoized fib(n) makes 2n − 1 calls; the time drops to O(n), at the price of O(n) memory.
- In tail recursion the call is the last thing the method does, and the intermediate result is carried in an accumulator parameter. Java does not optimize tail calls; the frames still pile up and the extra memory remains O(n).
- Integer overflow is different from stack overflow, and it is silent: long factorial(21) returns a negative number. Recursive methods are tested with the base case, one above the base case, invalid input and large input.
12.13Key terms
- recursion
- base case
- recursive case
- call stack
- stack frame
- recursion depth
- recursion tree
- helper method
- throw (an exception)
- palindrome
- greatest common divisor
- Euclid's algorithm
- substring
- divide and conquer
- binary search
- Towers of Hanoi
- subset
- backtracking
- stack overflow
- infinite recursion
- iterative version
- time complexity
- exponential growth
- Fibonacci sequence
- memoization
- tail recursion
- integer overflow
12.14Test Yourself
In the call sum(5) (sum(n) = n + sum(n − 1), sum(0) = 0), how many times is the sum method called? How many frames does the stack hold at its deepest moment, counting main? What is the result?
Answer
sum(5), sum(4), sum(3), sum(2), sum(1) and sum(0) are called: 6 calls. When sum(0) is called, no call has returned yet; with main there are 7 frames on the stack. The result is 5 + 4 + 3 + 2 + 1 + 0 = 15.
What is the chain of calls for gcd(21, 13)? How many calls are made and what is the result?
Answer
gcd(21, 13) → gcd(13, 8) → gcd(8, 5) → gcd(5, 3) → gcd(3, 2) → gcd(2, 1) → gcd(1, 0). In total 7 calls are made and the result is 1. 21 and 13 are consecutive Fibonacci numbers. For this reason the remainders also shrink one step at a time as Fibonacci numbers; this is the slowest case for Euclid's algorithm.
In the call fastPow(2, 13), what values does the exponent pass through? How many calls are made? Which frames multiply by the base once more on the way back? How many calls would plain power(2, 13) make?
Answer
The exponent is 13, 6, 3, 1 and 0: 5 calls. On the way back, the frames with an odd exponent (1, 3 and 13) multiply the result by 2 once more. The values are 1, 2, 8, 64 and 8192 in turn: 1·1·2 = 2, 2·2·2 = 8, 8·8 = 64, 64·64·2 = 8192. The plain method would make n + 1 = 14 calls.
How many moves are needed for 6 disks in the Towers of Hanoi? How many times is the hanoi method given in the notes called (counting the hanoi(0) calls)?
Answer
The number of moves is 2⁶ − 1 = 63. The number of calls is 2⁷ − 1 = 127: the number of calls doubles at each level of the recursion tree, and there are 7 levels (from n = 6 down to n = 0). All the leaves are hanoi(0) calls, which make no move.
When fib(10) is computed, how many calls do the plain recursive version and the memoized version make? Which formulas give the numbers?
Answer
The plain version makes 2·fib(11) − 1 = 2·89 − 1 = 177 calls. The memoized version makes 2·10 − 1 = 19 calls. The result is fib(10) = 55 in both.
The subsets method given in the notes is called with the array {1, 2, 3}. How many lines are printed? What is the 4th line? How many times is the method called?
Answer
2³ = 8 lines are printed: [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []. The 4th line is [1]: 1 is included, and 2 and 3 are excluded. The number of calls is 2⁴ − 1 = 15.
On the array a = {2, 5, 8, 12, 16, 23, 38, 56}, how many calls does search(a, 5, 0, 7) make, and what does it return?
Answer
In the first call mid = 3 and a[3] = 12; since 12 > 5, search(a, 5, 0, 2) is called. In this call mid = 1 and a[1] = 5: the value has been found. 2 calls are made and 1 is returned.
The tail-recursive version of the sum from 1 to n is:
static int sumTail(int n, int acc) { if (n == 0) return acc; return sumTail(n - 1, acc + n); }. What is the chain of calls for sumTail(4, 0)? In Java, how many frames are on the stack at the deepest moment, counting main?Answer
sumTail(4, 0) → sumTail(3, 4) → sumTail(2, 7) → sumTail(1, 9) → sumTail(0, 10) → 10. The additions are done before the calls and no work remains on the way back. Because Java does not optimize tail calls, all five sumTail frames are on the stack; with main there are 6 frames.
A method count(s, c, i) counts how many times a character occurs in a string, starting from index i. What should the base case and the recursive case be? How many calls does count("kayak", 'a', 0) make, and what does it return?
Answer
The base case is
i == s.length(): no characters are left to look at, and 0 is returned. In the recursive case, 1 is taken if s.charAt(i) equals c and 0 otherwise, and the value is added to count(s, c, i + 1). For “kayak”, 6 calls are made, for i = 0 to 5. The 'a' characters are at indices 1 and 3; the result is 2.
12.15Further reading
- R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 2.3: recursion is presented through Euclid's algorithm, the Towers of Hanoi, Gray codes and recursive graphics; the section also explains why direct Fibonacci is slow and how memoization speeds it up. The online version is at introcs.cs.princeton.edu.
- E. Roberts, Thinking Recursively with Java (Wiley, 2006): a book devoted entirely to thinking recursively. It builds, step by step, the habit of assuming the small problem is solved and constructing the big problem from it.
- A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019): recursive methods and stack diagrams are explained in plain language for people new to programming; the online version of the book is free.
- Oracle, Java SE 21 API: the official description of the StackOverflowError class; it states that the error is thrown when an application recurses too deeply.
12.16References
- E. Roberts, Thinking Recursively with Java, Wiley, 2006.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 2.3 Recursion.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
- Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, Java SE 21 API: StackOverflowError.
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
Related pages: Chapter 12 slides · Study questions · Recursion Visualizer simulator · Glossary · © Sercan Külcü. All rights reserved.