04 Recursion
04 Recursion
Recursion
The mirrors
Acknowledgement
The contents of these slides have origin from
School of Computing, National University of
Singapore.
We greatly appreciate support from Mr. Aaron
Tan Tuck Choy, and Dr. Low Kok Lim for
kindly sharing these materials.
2
Policies for students
These contents are only used for students
PERSONALLY.
Students are NOT allowed to modify or
deliver these contents to anywhere or anyone
for any purpose.
3
Objectives
• Strengthening the concept of recursion
1 learned in 501042 (or equivalent)
Book
• Chapter 3: Recursion: The Mirrors
• Chapter 6: Recursion as a
Problem-Solving Technique, pages
337 to 345.
Garfield dreaming
recursively.
Sierpinksi triangle
Droste effect
Recursive tree
Understanding Recursion
2.1 Recursion in 501042
In 501042, you learned simple recursion
No recursion on data structures
Code consists of ‘if’ statement, no loop
How to trace recursive codes
Examples covered in 501042
Factorial (classic example)
Fibonacci (classic example)
Greatest Common Divisor (classic example)
Other examples
Iterative solution
Recurrence relation
// Precond: n >= 0 // Precond: n >= 0
int fact(int n) { int fact(int n) {
int result = 1; if (n == 0)
for (int i=1;i<=n;i++) return 1;
result *= i; else
return result; return n * fact(n-
} 1);
}
Remember to document pre-conditions,
which are common for recursive codes. Base
Recursive case
call
[501043 Lecture 10: Recursion]
14
2.1 Recursion in 501042: Factorial (2/2)
120 Tracing recursion
fact(5) 5* fact(4) 24
fact(n):
if (n == 0) return 1;
4* fact(3)
6 else return n * fact(n-1);
3* fact(2)
2
2* fact(1)
1
1* fact(0) 1
1
[501043 Lecture 10: Recursion]
18
2.1 Recursion in 501042: Fibonacci (4/4)
Closed-form formula for Fibonacci numbers
Take the ratio of 2 successive Fibonacci numbers (say A and B).
The bigger the pair of numbers, the closer their ratio is to the
Golden ratio j which is 1.618034…
A 2 3 5 8 … 144 233
B 3 5 8 13 … 233 377
B/A 1.5 1.666… 1.6 1.625 … 1.61805… 1.61802…
See
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html
// Precond: a, b non-negative,
// not both zeroes
int gcd(int a, int b) {
int rem;
while (b > 0) {
rem = a % b;
a = b;
b = rem;
}
return a;
}
// Precond: a, b non-negative,
// not both zeroes
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
fact(5) 5 24 j =120
[501043 Lecture 10: Recursion]
25
3 Examples
CountDown.java
public class CountDown {
[501043 Lecture 10: Recursion]
27
3.2 Display an integer in base b
Example 2
See ConvertBase.java
E.g. One hundred twenty three is 123 in base 10; 173 in base 8
public static void displayInBase(int n, int base) {
if (n > 0) {
What is the
displayInBase(n / base, base);
System.out.print(n % base); precondition for
parameter base?
}
}
Example 1: Example 2:
n = 123, base = 8
n = 123, base = 10 123/8 = 15 123 % 8 = 3
123/10 =12 123 % 10 = 3 15/8 = 1 15 % 8 = 7
12/10 = 1 12 % 10 = 2 1/8 = 0 1 % 8 = 1
1/10 = 0 1 % 10 = 1 Answer: 173
Answer: 123
[501043 Lecture 10: Recursion]
28
3.3 Printing a Linked List recursively
Example 3
9
printLL
[501043 Lecture 10: Recursion]
29
3.4 Printing a Linked List recursively in
Example 4
reverse order
See SortedLinkedList.java and TestSortedList.java
public static void printRev
printLL (ListNode n) {
if (n!=null) {
printRev(n.next);
System.out.print(n.value); Just change the name!
System.out.print(n.value);
printRev
printLL (n.next); … Sure, right!
} head
}
printRev(head) printRev
5
printRev
Output:
8
9 8 5 printRev
9
printRev
[501043 Lecture 10: Recursion]
30
3.5 Sorted Linked List Insertion (1/2)
Example 5
v
p == null
v >= p.element
Case 3: Insert after p (recursion)
p.element
p.next p.element
insert ( p.next ,v)
final state
A B C
[501043 Lecture 10: Recursion]
34
3.6 Tower of Hanoi solution
Example 6
public static void Towers(int numDisks, char src, char dest, char temp) {
if (numDisks == 1) {
System.out.println("Move top disk from pole " + src + " to pole " + dest);
} else {
Towers(numDisks – 1, src, temp, dest); // first recursive call
Towers(1, src, dest, temp);
Towers(numDisks – 1, temp, dest, src); // second recursive call
}
}
while (stacktop>0) {
stacktop--; // pop current off stack
int numDisks = numDisksStack[stacktop];
char src = srcStack[stacktop]; char dest = destStack[stacktop];
char temp = tempStack[stacktop];
if (numDisks == 1) {
System.out.println("Move top disk from pole "+src+" to pole "+dest);
} else {
/* Towers(numDisks-1,temp,dest,src); */ // second recursive call
numDisksStack[stacktop] = numDisks -1;
srcStack[stacktop] = temp; Q: Which version runs faster?
destStack[stacktop] = dest; A: Recursive
tempStack[stacktop++] = src;
/* Towers(1,src,dest,temp); */ B: Iterative (this version)
numDisksStack[stacktop] =1;
srcStack[stacktop] = src; destStack[stacktop] = dest;
tempStack[stacktop++] = temp;
/* Towers(numDisks-1,src,temp,dest); */ // first recursive call
numDisksStack[stacktop] = numDisks -1;
srcStack[stacktop] = src; destStack[stacktop] = temp;
tempStack[stacktop++] = dest;
}
}
[501043 Lecture 10: Recursion]
37
3.6 Towers of Hanoi
Example 6
6 31+1+31 = 63 1 min
… … …
16 65,536 18 hours
32 4.295 billion 136 years
64 1.8 × 1010 billion 584 billion years
N 2N – 1
See Combination.java
X selected
choose k-1 out of n-1
or
choose k out of n
c(4,2)
Return c(3,1) + c(3,2)
c(3,1) c(3,2)
Return c(2,0) + c(2,1) Return c(2,1) + c(2,2)
[501043 Lecture 10: Recursion]
42
3.8 Searching within a sorted array
Example 8
x = 15
public class Permutations {
public static void main(String args[]) {
permuteString("", "String");
}
public static void permuteString(String beginningString, String endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0,i) + endingString.substring(i+1);
// newString is the endingString but without character at index i
permuteString(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
[501043 Lecture 10: Recursion]
49
Exercise: Eight Queens Problem
http://en.wikipedia.org/wiki/Eight_queens_puzzle