Recursion - Kirkwood Community College •A recursive method is a method that contains a call to...
Transcript of Recursion - Kirkwood Community College •A recursive method is a method that contains a call to...
Recursion
… just in case you didn’t love loops enough …
Recursion
• A recursive method is a method that contains a call to itself
• Often used as an alternative to iteration when iteration is awkward or “inelegant”
• Each recursive call is given a smaller portion of the original problem
• Last recursive call solves diminished problem without recursion
Example// method writes digits of a non-negative number, stacked verticallypublic void write_vertical(int n){
n = Math.abs(n);if (n < 10)
System.out.println(“” + n);else{
write_vertical(n / 10);System.out.println(“” + n % 10);
}}
Tracing recursive method write_vertical
1. write_vertical(52406); 52406
2. write_vertical(n/10) ; 5240
3. write_vertical(n/10); 524
4. write_vertical(n/10); 52
5. write_vertical(n/10); 5
n value: Output:
6. System.out.println(“” + n);
52406
7. System.out.println (“” + n%10);
8. System.out.println (“” + n%10);
9. System.out.println(n%10);
10. System.out.println (“” + n%10);public void write_vertical(int n){ n = Math.abs(n); if (n < 10) System.out.println(n); else { write_vertical(n / 10); System.out.println
(n % 10); }}
Elements of recursive method
• Base caseBase case: problem is simplified to the point where recursion becomes unnecessary: n < 10
• Variant expressionVariant expression: the part of the problem that changes, making the problem smaller: n
• Recursive callRecursive call: method calls itself: write_vertical (n / 10);
How recursion works
• Activation record: memory block that stores all the information a method needs to work:– values of local variables & parameters– where method should return to (so calling
method can resume execution)
How recursion works
• When a method call is encountered, execution of current method ceases
• Information for newly called method is stored in an activation record
• Method executes
How recursion works• If new method contains another method call, the
process just described repeats • Each recursive call generates its own activation
record– as each recursive call is encountered, previous
activation record is stored on run-time stack– when last call fails to generate a new activation
record, stacked calls are removed (in reverse of the order they were stored), and each process continues in succession
Remember, for a recursive method to be successful ...
• Must be a problem with one or more cases in which some subtasks are simpler versions of the original problem - use recursion for these
• Must also have one or more cases in which entire computation is accomplished without recursion (base case)
What is wrong with this picture?
// bad code:
public int sum (int n){
if (n < 0)return n;
elsereturn n + sum(n);
}
// Your corrected code:
Another example: the powers method
• Suppose you wanted to find the value of Xn
• For most values of n, we can solve this iteratively using a simple loop:int answer = 1;for (int c = 1; c <= n; c++)
answer *= X;• We can take care of the cases of n=1 or
n=0 with simple if statements; but what about a negative value of n?
Finding a recursive solution
• We can observe that for any value of n, Xn is equal to X * X(n-1)
• Armed with this information, we can easily develop a recursive solution that covers all values of X and n
Recursive power method
double rpower (double X, int n){
if (X == 0)return 0;
else if (n == 0)return 1;
else if (n > 0)return X * rpower(X, n-1);
else // n < 0return 1 / rpower(X, -n);
}
Drawing pictures with recursion• We used ASCII art to illustrate how iteration
worked – we can do the same with recursion• For example, if we wanted to draw a line using
several instances of a single character, we could write a loop like the one below:for (int x = lineLen; x > 0; x--)
System.out.print(“$ ”);• We can do the same task recursively; see next
slide
Example
public void drawLine (int x){
x = Math.abs(x);if (x == 0)
return;System.out.print(“$”);drawLine(x-1);
}
Trace this code with an initialx value of 5:
x value: output:
Same example, slightly different• The original iterative line drawing routine was
different from typical examples we’ve seen in the past, in that the counter was counting down instead of up
• I did this to illustrate how the iterative version relates to the recursive version – the problem (value of counter) gets smaller with each loop iteration, or each recursive call
• The situation is the same if we have the counter counting up, but it’s a little harder to see
ExampleIterative version:for (int x = 0; x < someConstant; x++)
System.out.print (“$ ”);Equivalent recursive version:public void drawLine (int x, int someConstant) {
if (x < someConstant) {System.out.print(“$”);drawLine (x+1, someConstant);
}}
Instead of x getting smaller, the distance betweendistance between x and someConstant gets smaller
Using the drawLine method, write a recursive drawSquare method:
// drawLine method:
public void drawLine (int x, int someConstant) {if (x < someConstant) {
System.out.print(“$”);drawLine (x+1, someConstant);
}}
// drawSquare method:
Drawing prettier pictures: random Fractals
• Fractals are mathematical phenomena that describe the kinds of seemingly random shapes that occur in nature
• Graphics programmers use fractals to draw natural-looking scenes
• Your textbook (as paraphrased on the next slide) describes one method for generating random fractals
Fractals made simple
1. Start with a line; find its midpoint:
2. Bend the line at the midpoint, using a random angle:
3. Lather, rinse, repeat:
An applet for fractals
• When we draw the lines that make up a fractal, we continually perform 3 tasks:– find the midpoint of a line– randomly generate a distance– draw two new lines, which stretch from a point
the generated distance above the midpoint to the points at the two ends of the original line
An applet for fractals• We keep performing the three tasks described,
breaking the original line into smaller and smaller segments until some end state is reached
• If we think of the end state as being the minimum distance we want to allow between any two points (or the minimum length of a line segment), we can come up with a recursive solution that starts with the original line length and stops when we have reached the minimum for each segment
The heart of the matter: the randomFractal method
public void randomFractal( int leftX, int leftY, int rightX, int rightY,Graphics drawingArea) {
final int STOP = 4; // When length < EPSILON, draw a line segment int midX, midY; // Midpoints in the x and y dimensions int delta; // Amount to shift the line's midpoint up or down if ((rightX - leftX) <= STOP) drawingArea.drawLine(leftX, leftY, rightX, rightY); else { midX = (leftX + rightX) / 2; midY = (leftY + rightY) / 2; delta = rg.nextInt(rightX - leftX); midY += delta; randomFractal(leftX, leftY, midX, midY, drawingArea); randomFractal(midX, midY, rightX, rightY, drawingArea); }}
Searching an array
• Think about the problem of searching for a value within an array
• With unsorted data, our only real option is to start at one end of the array and search until we either find the target value or exhaust all of the possibilities
• The method on the next slide illustrates such a process
Serial search – the brute force way
public int serialSearch(int n) { for (int x = 0; x < n; x++) if (array[x] == n) return x; return -1;}
What is the order of magnitude (big-O) for this method?
A recursive search method
• A more efficient search method can be defined recursively, and is somewhat analogous to the random fractal example:– check value at midpoint; if not target then– if greater than target, make recursive call to
search “upper” half of structure– if less than target, recursively search “lower”
half• Works only if data are sorted
Binary search code
public int binarySearch(int n, int first, int extent) { int mid = extent/2; if (extent == 0) return -1; else { if (array[mid] < n) binarySearch(n, first, extent/2); else if (array[mid] > n) binarySearch(n, mid+1, (extent-1)/2); return mid; } }
searching 28
Binary search in action
Suppose you have a 13-member array of sorted numbers:
5 14 23 47 59 71 82 99 108 113 130 151 172
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
Searching for value: 113Initial function call: first = 0,
extent = 13, mid = 6
searching 29
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Initial function call: first = 0,
extent = 13, mid = 6
Since 113 != 82, make recursive call:binarySearch (target, mid+1, (extent-1)/2);
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 30
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(1): first = 7,
extent = 6, mid = 10
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 31
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(1): first = 7,
extent = 6, mid = 10
Since 113 != 130, make recursive call:binarySearch(target, first, extent/2);
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 32
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(2): first = 7,
extent = 3, mid = 8
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 33
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(2): first = 7,
extent = 3, mid = 8
Since 113 != 108, make recursive call:binarySearch(target, mid+1, (extent-1)/2);
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 34
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(3): first = 9,
extent = 1, mid = 9
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 35
Binary search in action
5 14 23 47 59 71 82 99 108 113 130 151 172
Searching for value: 113Recursive call(3): first = 9,
extent = 1, mid = 9
Since 113 == 113, target is found; found = true, location = 9
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
searching 36
Binary Search Analysis• Worst-case scenario: item is not in the array
– algorithm keeps searching smaller subarrays– eventually, array size will be 0, and the search will
stop• Analysis requires computing time needed for
operations in function as well as amount of time for recursive calls
• We will analyze the algorithm’s performance in the worst case
searching 37
Step 1: count operations• Test base case: if (extent==0) 1 operation• Compute midpoint:
mid = first + extent/2; 3 operations• Test for target at midpoint:
if (target == array[mid]) 2 operations• Test for which recursive call to make:
if (target < array[mid]) 2 operations• Recursive call - requires some arithmetic and
argument passing - estimate 10 operations
searching 38
Step 2: analyze cost of recursion
• Each recursive call is preceded by 18 (or fewer) operations
• Multiply this number by the depth of recursive calls and add the number of operations performed in the stopping case to determine worst-case running time (T(n))
• T(n) = 18 * depth of recursion + 3
searching 39
Step 3: estimate depth of recursion
• Calculate upper bound approximation for depth of recursion; may slightly overestimate, but will not underestimate actual value– Each recursive call is made on an array segment
that contains, at most, N/2 elements– Subsequent calls are always made on size/2– Thus, depth of recursion is, at most, the number of
times N can be divided by 2 with a result > 1
searching 40
Estimating depth of recursion
• Referring to “the number of times N is divisible by 2 with result > 1” as H(n), or the halving function, the time expression becomes:T(n) = 18 * H(n) + 3
• H(n) turns out to be almost exactly equal to log2n: H(n) = log2n meaning that fractional results are rounded down to the nearest whole number (e.g. 3.7 = 3) -- this notation is called the floor function
searching 41
Worst-case time for binary search
• Substituting the floor function of the logarithm for H(n), the time expression becomes:T(n) = 18 * ( log2n ) + 3
• Throwing out the constants, the worst-case running time (big O) function is: O(log n)
searching 42
Significance of logarithms
• Logarithmic algorithms are very fast because log n is much smaller than n
• The larger the data set, the more dramatic the difference becomes:– log28 = 3– log264 = 6– log21000 < 10– log21,000,000 < 20
searching 43
For binary search algorithm...
• To search a 1000 element array will require no more than 183 operations in the worst case
• To search a 1,000,000 element array will require less than 400 operations in the worst case
When Not to Use Recursion
• When recursive algorithms are designed carelessly, it can lead to very inefficient and unacceptable solutions
• In general, use recursion if– A recursive solution is natural and easy to
understand.– A recursive solution does not result in excessive
duplicate computation.– The equivalent iterative solution is too complex.
Preventing infinite recursion
• One-level recursion: every case is either a stopping case or makes a recursive call to a stopping case
• Since most recursive functions are, or have the potential to be, recursive beyond just one level, need more general method for determining whether or not recursion will stop
Preventing infinite recursion
• Define a variant expressionvariant expression– numeric quantity that decreases by a fixed
amount on each recursive call• Base case is when variant expression is
less than or equal to its threshold valuethreshold value
Recursive backtracking
• Recursion is best used for solving problems that don’t lend themselves easily to iteration
• An example of this type of problem is exemplified by a maze traversal
• The recursive solution strategy for this type of problem is called exhaustive search with backtracking
Traversing a maze
• There are 4 important rules for getting through a maze:– don’t run into walls– remember where you’ve been– only go where you haven’t been– when you reach the goal, go back the way
you came in (assuming that “goal” wasn’t just to get out of the maze!)
Pseudocode for maze traversal
1. Face left (initial direction)2. for (three possible directions) {
if (goal not reached && not facing wall) {Explore current directionReturn to same spotif (goal reached)
found = true}
Turn right}
• Step forward and turn around
Helper methods public static boolean deadend( ) {
returninquire("Are you facing a wall?") ||inquire("Is your name written in front of you?");
}
// Specification for inquire method:// precondition: query is a String containing the question to be asked// postcondition: prints query and takes in user response; if response is ‘y’ or ‘Y’// returns true; if response is ‘n’ or ‘N’ returns false
Maze traversal method
public static boolean traverseMaze( ) { int direction; // Counts 1, 2, 3 for the three directions to explore boolean found; // Will be set to true if we find the tapestry
System.out.println("Step forward & write your name on the ground."); found = inquire("Have you found the tapestry?");
if (found) { // Pick up the tapestry and step back from whence you came. System.out.println("Pick up the tapestry and take a step backward."); }
Maze traversal, continuedelse // not found { // Explore the three directions (not counting the one that you just came from). Start // with the direction on your left, and then turn through each of the other directions. System.out.println("Please turn left 90 degrees."); for (direction = 1; direction <= 3; direction++) { if ( !found && !deadend( ) ) found = traverseMaze( ); System.out.println("Please turn right 90 degrees."); } // You’re now facing the direction from whence you came, so step forward and turn // around. This will put you in the same spot when the method was activated. System.out.println("Please step forward, then turn 180 degrees."); } return found; }
One more example: Teddy Bear game
• Starting condition: you have a certain known number of bears (initial)
• Your goal is to end up with a different known number of bears (goal)
• You are allowed a certain number of steps (n) to get to goal
• Game ends when either:– goal reached or– n == 0
Playing Teddy Bear
• To play game, you can do one of the following things at each step:– increase the number of bears in your hand by
a fixed amount (increment)– if you have an even number of bears, you can
cut that number in half• Example:
– initial = 99, goal = 91, increment = 53, n = 4– 99 (inc) 152 (cut) 76 (cut) 38 (inc) 91 (GOAL!)
Teddy Bear Code public static boolean bears(int initial, int goal, int increment, int n) { if (initial == goal) return true; else if (n == 0) return false; else if (bears(initial+increment, goal, increment, n-1)) return true; else if ((initial % 2 == 0) && bears(initial/2, goal, increment, n-1)) return true; else return false; }