You are on page 1of 48

Chapter 7

Recursion
What is Recursion?
• A recursive method is a method that either
directly or indirectly makes a call to itself.
• Examples:
– Files on a computer are generally stored in
directories.
– Users may create subdirectories that store more
files and directories.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2


What is Recursion? (2)
– Suppose that we want to examine every file
in a directory D, including all files in all
subdirectories (and subsubdirectories, and so
on).
– We do so by recursively examining every
file in each subdirectory and then examining
all files in the directory D.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-3


Recursion: Example #1

public class recExample {


public static long s(int n) {
if ( n == 1 )
return 1;
else
return s(n-1)+ n;
}
public static void main (String [] args) {
System.out.println (s(10));
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-4


Recursion: Example (2)
s(10)
s(9) + 10
s(8) + 9 + 10
s(7) + 8+ 9 + 10
s(6) + 7 + 8 + 9 + 10
s(5) + 6 + 7 + 8 + 9 + 10
s(4) + 5 + 6 + 7 + 8 + 9 + 10
s(3) + 4 + 5 + 6 + 7 + 8 + 9 + 10
s(2) + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
s(1) + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10
1 + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-5
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-6
Recursion: Example #2
public class recExample {
static int i=0;
public static void s(int n) {
if ( n > 1 ){
i++;
s(n-1);
}
System.out.println (i+ "#");
}
public static void main (String [] args) {
s(10);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-7


Activation Record & Stack

procedure ARDemo( i:uns32; j:int32; k: boolean );


var
a: int32;
r: real32;
c: char;
b: boolean;
w: word;
begin ARDemo;

end ARDemo; Activation Record for ARDemo

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-8


Activation Record
class activationRecord {
static void print_facts(int num1, int num2){
int larger;
double the_avg;
// point 3
larger = max_of_two(num1, num2);
// point 6
the_avg = avg_of_two(num1, num2);
// point 9
System.out.println ("For the two integers " + num1 +
" and " + num2 +',');
System.out.println ("the larger is " + larger + "
and the average is " + the_avg +'.');
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-9
static int max_of_two (int j, int k) {
// point 4
if (j < k)
j = k;
// point 5 Activation Record(2)
return j;
}
static double avg_of_two (int c, int d) {
double sum;
// point 7
sum = c + d;
// point 8
return (c + d) / 2.0;
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-10


public static void main(String []args){
int i;
int j;
// point 1
i = -8; Activation Record(3)
j = 7;
// point 2
activationRecord aR =new activationRecord();
aR.print_facts(i,j);
//point 10
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-11


Activation Record(4)

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-12


Activation Record(5)

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-13


Recursion: Example (3)

• Although s seems to be calling itself, in


reality it is calling a clone of itself.
• That clone is simply another method with
different parameters.
– Base case: Always have at least one case that
can be solved without using recursion.
– Make progress: Any recursive call must
progress toward a base case.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-14


Recursion: Problems

• Previous recursive evaluation routine does


have a few problems. The first problem is
the call s (0), for which the method behaves
poorly.
• Fix this problem by extending the definition
of S(N) to include N = 0.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-15


Recursion: Problems (2)

• A second problem is that if the parameter n


is large, but not so large that the answer
does not fit in an int, the program can crash
or hang.
• Our system, for instance, cannot handle
N>= 8,882.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-16


Fibonacci Number
• The Fibonacci numbers form a sequence
defined by the following recurrence relation:

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-17


Fibonacci Number (2)

• Fn, for n = 0, 1, … , are:


– 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610, 987, 1597, 2584, 4181,
6765, 10946, 17711, 28657, 46368,
75025, 121393, 196418, 317811…

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-18


Fibonacci Number (3)

F(4) = F(3) +F(2)


F(4) = (F(2) + F(1)) + (F(1) + F(0)
F(4) = (F(1) + F(0)) + 1 + 1 + 0
F(4) = 1 + 0 + 1 + 1 + 0
F(4) = 3

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-19


public class fibExample {
static int fib (int num){
switch(num) {
case 0:
return(0); Fibonacci Number (4)
case 1:
return(1);
default:
return (fib(num - 1) + fib (num - 2));
}
}
public static void main (String [] args) { Output
System.out.println (fib(5)); 5
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-20
public class fibExample1{
public static int fib(int num) {
if ( num == 0 )
return 0;
else if ( num == 1 )
return 1; Fibonacci Number (5)
else
return(fib(num - 1) + fib(num - 2));
}
public static void main (String [] args) {
Output
System.out.println (fib(6));
} 8
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-21
Recursions: Problems

• Too many recursions


• Redundant calculations:
fib (n) = fib (n-1) + fib (n-2)
• Normally, making two calls instead of one
would only double the running time of a
program

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-22


Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-23
Factorial

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-24


Factorial: Recursion

5! = 5 x 4!
5! = 5 x 4 x 3!
5! = 5 x 4 x 3 x 2!
5! = 5 x 4 x 3 x 2 x 1!
5! = 5 x 4 x 3 x 2 x 1! = 120
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-25
Factorial: Recursion (2)
public class factExample {
public static int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial (n-1);
}
public static void main (String [] args) {
System.out.println (factorial(7)); Output
} 5040
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-26
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-27
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-28
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-29
Print n in Base 10, n >= 0
public class printExample {
public static void printDecimal (long n){
if( n >= 10 )
printDecimal (n/10);
System.out.print("Point 1 -->");
System.out.println (" " +(char) ('0' + ( n %
10)));
} Output
public static void main (String [] args) { Point 1 --> 1
printDecimal (177); Point 1 --> 7
System.out.print ((int)('0')); Point 1 --> 7
} 48
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-30
ASCII Table

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-31


Greatest Common Divisor
public class gcdExample {
public static long gcd (long a, long b){
if (b == 0)
return a;
else {
System.out.println ("a % b = " + a % b);
return gcd (b, a % b);
}
}
Output
public static void main (String [] args) {
a%b=9
System.out.println(gcd(81,36)); a%b=0
} 9
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-32
Greatest Common Divisor

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-33


Power Function: x n

public class powerExample {


public static int power (int x, int n) {
if (n <= 0)
return 1;
if (n == 1)
return x;
return (x * power(x, n-1));
}
public static void main (String [] args) { Output
System.out.println(power(10,3)); 1000
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-34
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-35
Example #1
class myClass {
static void myMethod (int counter) {
if (counter == 0)
Output
return;
10
else {
9
System.out.println (""+counter);
8
myMethod (--counter);
7
return;
6
}
5
}
4
public static void main (String [] args) { 3
myMethod(10); 2
} 1
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-36
Example #2
public class sumExample {
public static int SumSquares (int n) { Output
if (n < 1) 55
return 0;
else
return (n * n + SumSquares (n - 1));
}
public static void main (String [] args){
System.out.println (SumSquares (5));
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-37
Example #2 (2)

SumSquares (5)= 25 + SumSquares (4)


SumSquares (5)= 25 + 16 +SumSquares (3)
SumSquares (5)= 41+9 + SumSquares (2)
SumSquares (5)= 50+4 + SumSquares (1)
SumSquares (5)= 54+1 + SumSquares (0)
SumSquares (5)= 55+ 0
SumSquares (5)= 55

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-38


Towers of Hanoi

• The object of the game is to move the disks,


one at a time, to the third peg. The catch is
that a disk cannot be placed on top of one of
that is smaller in diameter.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-39


Towers of Hanoi (2)

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-40


Towers of Hanoi (2)
class TowersApp {
static int nDisks = 3;
public static void main(String[] args) {
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char src, char inter, char dest) {
if(topN==1)
System.out.println("Disk 1 from " + src + " to "+ dest);
else {
doTowers(topN-1, src, dest, inter);
System.out.println("Disk " + topN + " from " + src + " to "+ dest);
doTowers(topN-1, inter, src, dest);
}
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-41


Towers of Hanoi (3)
Output
• Disk 1 from A to C
• Disk 2 from A to B
• Disk 1 from C to B
• Disk 3 from A to C
• Disk 1 from B to A
• Disk 2 from B to C
• Disk 1 from A to C
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-42
Binary Search Example

• Recursive binary search of sorted array.


• The upper bound index is not included in
the search.
• The performance is O(log N).

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-43


Binary Search Example (2)
public static int rBinarySearch (int[] sorted, int first, int upto, int key) {
if (first < upto) {
int mid = first + (upto - first) / 2; // Compute mid point.
if (key < sorted[mid]) {
return rBinarySearch(sorted, first, mid, key);
} else if (key > sorted[mid]) {
return rBinarySearch(sorted, mid+1, upto , key);
} else {
return mid; // Found it.
}
}
return -(first + 1); // Failed to find key
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-44


Linked Lists
• Write a method for RecursiveList which counts
the number of elements in the list.
public static int length (LN l) {
if (l == null)
return 0;
else
return 1 + length (l.next);
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-45


Linked Lists (2)
• Write a method for RecursiveList to print the contents of
a RecursiveList.
public static void display (LN l) {
if (l != null) {
display(l.next);
System.out.println(l.value);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-46


Linked Lists (3)

• Compute the sum of all the values in the nodes of


a linked list.
public static int sum (LN l) {
if (l == null)
return 0;
else
return l.value + sum(l.next);
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-47
Reverse SSL
public void reverse() {
Node current = head;
head = null;
while (current != null) {
Node temp = current;
current = current.next;
temp.next = head;
head = temp;
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-48

You might also like