recursion. canonical example: factorial recursion when a method calls itself classical example –...
TRANSCRIPT
Recursion
Canonical example: factorial
Recursion When a method calls itself
Classical example – the factorial function n! = 1· 2· 3· ··· · (n-1)· n
Recursive definition
elsenfn
nnf
)1(
0 if1)(
Example I using recursion: Sum of values from 1 to N Problem
computing the sum of all the numbers between 1 and N
This problem can be recursively defined as:
3
1
2
1
1
11
21
1
N
i
N
i
N
i
N
i
iNNN
iNNiNi
Example I using recursion: Sum of values from 1 to N (ctd)
// This method returns the sum of 1 to num// Refer to SumApp projectpublic int sum (int num){ int result;
if (num == 1) result = 1; else result = num + sum (n-1);
return result;}
Example I using recursion: Sum of values from 1 to N (ctd)
main
sum
sum
sum
sum(3)
sum(1)
sum(2)
result = 1
result = 3
result = 6
Content of recursive definition Base case (s)
Values of the input variables for which no recursive calls are performed
There should be at least one base case
Every chain of recursive calls must Eventually reach a base case
Recursive calls Calls to the current method
Defined in such a way that It makes progress towards a base case
Example II using recursion: Factorial Factorial of a positive integer n, written n! is the product
n · (n – 1) · (n – 2) · … · 1 with 1! equal to 1 and 0! defined to be 1
The factorial of integer number can be calculated iteratively (non-recursively) using a for statement as follows:
factorial = 1; for(int counter = number; counter >= 1; counter-- ) factorial *= counter;
Recursive declaration of the factorial method is arrived at by observing the following relationship:
n! = n · (n – 1)!
Example II using recursion: Factorial (cont’d)
long should be used so that the program can calculate factorials greater than 12!
Package java.math provides classes BigInteger and BigDecimal explicitly for
high precision calculations not supported by primitive types.
Refer to FactorialApp project
Example II using recursion: Factorial (cont’d) BigInteger method compareTo
compares the BigInteger that calls the method to the method’s BigInteger argument.
Returns -1 if the BigInteger that calls the method
is less than the argument, 0 if they are equal or 1 if the BigInteger that calls the method
is greater than the argument.
BigInteger constant ONE represents the integer value 1. ZERO represents the integer value 0.
Example III using recursion: Fibonacci Series The Fibonacci series, begins with 0 and 1 and
has the property that each subsequent Fibonacci number is the sum of the previous two.
0, 1, 1, 2, 3, 5, 8, 13, 21, …
The ratio of successive Fibonacci numbers converges to a constant value of 1.618…,
called the golden ratio or the golden mean.
The Fibonacci series may be defined recursively: fibonacci(0) = 0fibonacci(1) = 1fibonacci(n) = fibonacci(n–1) + fibonacci(n–2)
Example III using recursion: Fibonacci Series Two base cases for Fibonacci method
fibonacci(0) is defined to be 0 fibonacci(1) to be 1
Fibonacci numbers tend to become large quickly. We use type BigInteger as the the return type of
The fibonacci method
BigInteger methods multiply and subtract implement multiplication and subtraction.
Refer to FibonacciApp project
Visualizing Recursion for Factorial
Recursion trace
A box for each recursive call
An arrow from each caller to callee
An arrow from each callee to caller showing return value
Example recursion trace:
recursiveFactorial(4)
recursiveFactorial(3)
recursiveFactorial(2)
recursiveFactorial(1)
recursiveFactorial(0)
return 1
call
call
call
call
return 1*1 = 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24 final answercall
Example IV using recursion: Binary Search A binary search
Assumes the list of items in the search pool is sorted
Eliminates a large part of search pool with 1 comparison
Examines the middle element of the list If it matches the target, the search is over
Otherwise, only one half of the remaining elements Need to be searched
Then examines the middle element of remaining pool
Eventually, the target is found or data is exhausted
Example IV using recursion: Binary Search (cont’d) Example:
Search a sorted array for a given value
BS(A, key, start, end) Look for key in the array A
where elements are sorted according to ascending order
A method that calls itself with a smaller input set
start: index of 1st element in search pool
end: index of 1st element in search poolmiddle
A
Binary search recursion: pseudo-code// Refer to BinarySearchApp project
Boolean BS(A, key, start, end)mid = (start+end)/2if(A[mid] == key)
return trueelse
if(end <= start)return false
elseif (A[mid] > key)
return BS(A, key, start, mid-1)else
return BS(A, key, mid+1, end)
Example V using recursion: Towers of Hanoi Given
A platform with three pegs sticking out of it
Each peg is a stack that can accommodate n disks
Puzzle Move all disks from peg a to peg c, one disk at a time
So that we never place a larger disk on top of smaller one
Refer to TowersOfHanoiApp project
Towers of Hanoi
Original Configuration Move 1
Move 3Move 2
Towers of Hanoi
Move 4 Move 5
Move 6 Move 7 (done)