This lesson introduces a new problem solving strategy called recursion. Recursion represents an exciting new addition to our algorithm toolbox. It can be hard to wrap your head around at first. But we’ll go slow and, as always, use lots of examples. What are we waiting for?
So far we’ve looked exclusively at iterative algorithms that solve a problem by repeating a series of steps.
The implementations of iterative algorithms are characterized by the use of looping constructs such as for and while.
Recursive algorithms work differently. They solve problems by breaking them down into smaller yet similar pieces, and the reassembling the solutions to the smaller problems into a solution to the larger problem. This will make more sense once we look at some examples!
But let’s start by examining both the general definition of recursion and how recursion is used in computer science.
Learning to think recursively takes time and practice. You’ll get both!
But let’s start by comparing and contrasting an iterative and recursive solution to the same problem. That will both help us start to learn to think recursively, and identify the differences between the two approaches.
Let’s write an algorithm to determine if a String is a palindrome, that is, whether it reads the same forwards and backwards.
First, let’s design an iterative algorithm:
Next, let’s try and approach the problem recursively.
What does that mean? A recursive solution tries to make the problem smaller in each step until it is trivial to solve. Let’s think about how to apply that to palindrome detection.
To wrap up, let’s put the two approaches side by side and discuss the differences.
A recursive implementation contains a function that calls itself. At first, this may seem really weird. But the trick is not to not let that throw you, and to just consider what happens.
Successful recursive algorithms must do three things correctly:
Let’s examine another recursive implementation. We’ll identify the three requirements enumerated above, and trace its execution.
The next homework problem has you complete a recursive implementation of factorial. For reference, here is the iterative implementation that matches the homework problem:
To complete the recursive implementation, consider the following questions:
Create a public class Factorial that provides a single static method factorial.
factorial accepts a single long and returns its factorial as a long.
You can reject negative arguments and ones greater than 20 by throwing an IllegalArgumentException.
You should submit a recursive solution. The factorial of 0 is 1, and this represents the base case. The factorial of n is n * the factorial of n - 1, and this represents the recursive step.
As a reminder: In CS 124, in addition to teaching you how to write correct code, we also want to teach you how to write good code: Code that’s beautiful and elegant and that you and those you work with will be proud of.
There are multiple aspects of code quality that we’ll be introducing throughout the semester.
Previously we talked about ensuring beautiful code formatting using checkstyle, removing unnecessary debugging output, eliminating dead code, avoiding overly-long code, and reducing code complexity.
checkstyle rules are now enforced on homework and quizzes, and starting today, there will be a one-point deduction for correct submissions that produce unnecessary debugging output, contain dead code, are much longer than the reference solution, or are unnecessarily complex.
The next aspect of code quality we’ll discuss is execution efficiency, which we measure by the number of lines that your submission executes. CS 124 is not a course on code optimization or one that places a significant premium on execution efficiency. However, we still do want you to avoid submitting code that is way more inefficient than the reference solution.
Let’s see an example of how that works using a familiar practice problem:
We’ll be warning you about significantly inefficient programs starting today, and in a few weeks you’ll lose one point on the graded homework if you don’t reduce the execution count appropriately.
Create a class RangeSum with a public static method sum that accepts a single int value and returns the sum
of all the integers in the range 1..value as an int.
So, for example, given the input 10 you should return 55: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10.
You can reject arguments less than or equal to 0 and ones greater than 128 by throwing an
IllegalArgumentException.
You should submit a recursive solution. The range sum of 1 is 1, and this represents the base case. The range sum of n is n + the range sum of n - 1, and this represents the recursive step.
Need more practice? Head over to the practice page.