lecture 9
lecture 9
2x
Introduction to Java Programming – Part 2
Lecture 4
T.C. Pong
Department of Computer Science & Engineering
HKUST
Lecture 4
Recursion
Example: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person.
What is the total number of handshakes h(n)?
Example: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person.
What is the total number of handshakes h(n)?
h(2) = 1
Example: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person.
What is the total number of handshakes h(n)?
h(3) = h(2) + 2 h(2) = 1
Example: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person.
What is the total number of handshakes h(n)?
h(4) = h(3) + 3 h(3) = h(2) + 2 h(2) = 1
Example: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person.
What is the total number of handshakes h(n)?
h(n) = h(n-1) + n-1 h(4) = h(3) + 3 h(3) = h(2) + 2 h(2) = 1
Recursion
• In some problems, it may be natural to define
the problem in terms of the problem itself.
• Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
• Consider for example the factorial function:
6! = 6 * 5 * 4 * 3 * 2 * 1
fact3 = 3 * 2 = 6
return fact3
fact(3) has the value 6
Recursion
For certain problems (such as the factorial function), a recursive solution
often leads to short and elegant code. Here is a comparison of the
recursive solution with the iterative solution:
public static int fact(int n){ public static int fact(int n){
int t = 1; if(n<=1)
int counter = 1; return 1;
else
return n * fact(n-1);
while (counter <= n) { }
t = t * counter;
counter = counter + 1;
}
return t;
}
Recursion: Handshake problem
• Total number of handshakes for n persons:
h(n) = h(n-1) + (n-1)
• Implement h(n) using a recursive method:
public static int handShake(int n){
if(n <= 2)
return n - 1;
else
return handShake(n-1) + (n-1);
}
• Alternative implementation:
Sum of integers from 1 to n-1 = n(n-1) / 2
Recursion
• When we use recursion we must be careful not to
create an infinite chain of recursive method calls:
public int fac(int n){
return n * fac(n-1);
} // Oops! no termination condition
or:
public int fact(int n){
if (n<=1)
return 1;
else
return n * fact(n+1); // Oops!
}
Example: Fibonacci Sequence
How many pairs of rabbits can be produced from a
single pair in a year's time?
• Assumptions:
– Each pair of rabbits produce a new pair of offspring every month;
– each new pair becomes fertile at the age of one month;
– none of the rabbits dies in that year. “True Albino”
by Tomi Tapio K
is licensed under CC BY 2.0
• Example:
– After 1 month there will be 2 pairs of rabbits;
– after 2 months, there will be 3;
– after 3 months, there will be 5 (since the following month the original pair and
the pair born during the first month will both produce in a new pair and there
will be 5 in all).
Computation Methods
• Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Number of
where each number is the sum of the
Rabbit Pairs preceding two.
1
1
• Recursive definition:
2
– F(0) = 0;
– F(1) = 1;
3
– F(n) = F(n-1)+ F(n-2);
5
Computing Fibonacci numbers
//Calculate Fibonacci numbers using recursive method
public class Fibonacci
{
static int fib(int n){
if (n == 0) return 0;
if (n == 1) return 1;
return (fib(n-1) + fib(n-2));
}
fib(3) fib(2)
fib(1) fib(0)
Fibonacci Numbers
• Fibonacci numbers can also be represented by the following
formula.
Other Recursive Applications
• Binary search:
– Given a sorted array, the binary search find
an element in the array efficiently.
• Compare search element with middle
element of the array
• If not equal, then apply binary search to
half of the array (if not empty) where
the search element could be found
Binary Search with Recursion
/**
* @param data input array
* @param lower lower bound index
* @param upper upper bound index
* @param value value to search for
* @return index if found, otherwise return -1
*/
public int binSearch(int[] data, int lower, int upper, int value)
{
int middle = (lower + upper) / 2;
if (data[middle] == value)
return middle;
else if (lower >= upper)
return -1;
else if (value < data[middle])
return binSearch(data, lower, middle-1, value);
else
return binSearch(data, middle+1, upper, value);
}
The Towers of Hanoi
• According to legend, monks in a remote monastery
could predict when the world would end.
– They had a set of 3 diamond needles.
– Stacked on the first diamond needle were 64 disks of
decreasing size.
– Their task is to move all the disks from one needle to
another by following certain rules.
Moving third
disk from A to C
Recursive calls
The Towers of Hanoi
Non-recursive step
The Towers of Hanoi