You are on page 1of 44

RECURSION

Learn about recursive definitions Explore the base case and the general case of a

recursive definition Discover what a recursive algorithm is Learn about recursive methods Explore how to use recursive methods to implement recursive algorithms Learn how recursion implements backtracking
2

Data Structures Using Java

How we could write our own recursive method for finding

string length? To solve the problem : Recursive

Recursion
Process of solving a problem by reducing it to

smaller versions of itself

Recursive definition
Definition in which a problem is expressed in terms

of a smaller version of itself Has one or more base cases

Data Structures Using Java

Recursive algorithm Algorithm that finds the solution to a given problem by reducing the problem to smaller versions of itself Has one or more base cases Implemented using recursive methods Recursive method Method that calls itself Base case Case in recursive definition in which the solution is obtained directly Stops the recursion
Data Structures Using Java

General solution
Breaks problem into smaller versions of itself

General case
Case in recursive definition in which a smaller

version of itself is called Must eventually be reduced to a base case

Data Structures Using Java

Directly recursive: a method that calls itself Indirectly recursive: a method that calls another

method and eventually results in the original method call Tail recursive method: recursive method in which the last statement executed is the recursive call Infinite recursion: the case where every recursive call results in another recursive call

Data Structures Using Java

The ability of a procedure or function to call itself. A

kind of programming in which a procedure may call itself as a subroutine. Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that would be difficult to solve in other ways Recursion splits a problem into one or more simpler versions of itself

Recursion is an alternative to iteration

Iterative solutions use loops or iterate through every

instance of the problem

There are similarities between recursion and iteration In iteration, a loop repetition condition determines

whether to repeat the loop body or exit from the loop

In recursion, the condition usually tests for a base case You can always write an iterative solution to a problem

that is solvable by recursion Recursive code may be simpler than an iterative algorithm and thus easier to write, read, and debug But in some cases, a recursive approach is not so efficient because it consumes so much memoy.

Iteration Recursive

recursive algorithm: description for a way to solve a

problem, that refers to itself Show everything in a folder and all it subfolders:

1. show everything in top folder 2. show everything in each subfolder in the same manner

if (base case) { return something easily computed } else { divide problem into pieces return something calculated from the solution to each pieces }

Recursive method: method that calls itself A recursive method has two cases:
Base case : case in recursive definition in which the

solution is obtained directly or a simple case of the problem that can be answered directly (does not use recursion)

Recursive/General case: case in recursive definition in

which a smaller version of itself is called or a more complicated case of the problem, that isn't easy to answer directly, but can be expressed elegantly with recursion (makes a recursive call to help compute the overall answer)

Understand problem requirements Determine limiting conditions Identify base cases Provide direct solution to each base case Identify general case(s) Provide solutions to general cases in terms of smaller

versions of itself

Data Structures Using Java

19

Recursive method

Has unlimited copies of itself Every recursive call has its own code own set of parameters own set of local variables

Data Structures Using Java

20

After completing recursive call


Control goes back to calling environment Recursive call must execute completely before

control goes back to previous call Execution in previous call begins from point immediately following recursive call

Data Structures Using Java

21

Look up a word in a dictionary:

1. look up the word using the alphabetical

ordering. 2. if all words in the definition are known to you, stop. 3. else, for each unknown word in the definition, look up that word

How we could write our own recursive method for

finding string length? Solution:

The base case is an empty string : its length is 0 The recursive case, each string has two parts: the first

character and the rest of the string. If we can find the length of the rest of the string, we can then add 1(for the first character) to get the length of the larger string. Example: the length of abcde is 1 + the length of bcde

if the string is empty(has no characters) the length is 0 else the length is 1 plus the length of the string that excludes the first character.

public static int length( String str ) { if ( str == null || str.equals("")) return 0; else return 1 + length(str.substring(1)); }

The factorial of n or n!, is defined as follows:


0! = 1 base case n! = n x (n-1)! recursive case

Recursive algorithm for computing n!


if n equals 0 n! is 1 else n! = n x (n-1)!

public static int factorial( int n ) { if ( n == 0 ) return 1; else return n * factorial( n-1 ); }

Recursive proof
Verify the base case is recognized and solved correctly Verify that each recursive case makes progress towards

the base case Verify that if all smaller problems are solved correctly, then the original problem is also solved correctly

Write a recursive method named square(N) that

implements this definition of square numbers:


square(1) = 1 Square(3) = square(2) + 6 - 1 square(N) = square(N-1) + 2*N -1

public static int square( int N ) { if ( N == 1 ) return 1; else return square(N-1) + 2*N -1; }

Given the following formula:


Sum (3) = 3*3 + 2*2 + 1*1 Sum (5) = 5*5 + 4*4 + 3*3 + 2*2 + 1*1 Sum (n) = (n*n) + ((n-1)*(n-1)) + ((n-2)*(n-2)) + ...... + 1*1

Write a recursive method named sum (N) in Java

code that returns the sum of the calculation as shown above.

public static int sum( int n ) { if ( n == 1 ) return 1; else return n * n + (sum( n-1 )); }

Given the following Java application:


public class Recursive { public static void main(String args []) { String num; int n; num = JOptionPane.showInputDialog("Enter value n: "); n = Integer.parselnt(num); System.out.printIn("Output = " + Calculate(5,n) ); } }

The method Calculate will compute 5n. Write the

recursive definition for this method. Trace the recursive function for n = 4.

public static int Calculate(int x, int n) { if (n == 0) return 1; else return x * Calculate(x, n-1); }

Consider the following method:


public static int mystery1(int x, int y) { if (x < y) { return x; } else { return mystery1(x - y, y); } }

Tracing recursive methods, For each call below, indicate what value is returned: mystery1(6, 13) mystery1(14, 10) mystery1(37, 10) mystery1(8, 2) mystery1(50, 7)

public static void mystery2(int n) { if (n <= 1) { System.out.print(n); } else { mystery2(n / 2); System.out.print(", " + n); } }

Tracing recursive methods, For each call below, indicate what value is returned: mystery2(1) mystery2(2) mystery2(3) mystery2(4) mystery2(16) mystery2(30) mystery2(100)

public static int mystery3(int n) { if (n < 0) { return -mystery3(-n); } else if (n < 10) { return n; } else { return mystery3(n/10 + n % 10); } }

Tracing recursive methods, For each call below, indicate what value is returned: mystery3(6) mystery3(17) mystery3(259) mystery3(977) mystery3(-479)

public static void mystery4(String s) { if (s.length() > 0) { System.out.print(s.charAt(0)); if (s.length() % 2 == 0) { mystery4(s.substring(0, s.length() - 1)); } else { mystery4(s.substring(1, s.length())); } System.out.print(s.charAt(s.length() - 1)); } }

Tracing recursive methods, For each call below, indicate what value is returned: mystery4(") mystery4("a) mystery4("ab) mystery4("bc) mystery4("abcd)

Past Year
Question 7 Sept 2011 Question 6 b) Apr 2010 Question 5- Oct 2010

You might also like