Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion.

Similar presentations


Presentation on theme: "Recursion."— Presentation transcript:

1 Recursion

2 Canonical example: factorial
Recursion When a method calls itself Classical example – the factorial function n! = 1· 2· 3· ··· · (n-1)· n Recursive definition Recursion is used for performing repetitive tasks. To illustrate recursion, let us begin with a simple example of computing the value of the factorial function. The factorial of a positive integer n, denoted n!, is defined as the product of the integers from 1 to n. If n=0, then n! is defined as 1 by convention. The factorial function can be defined in a manner that suggests a recursive formulation. Factorial(5) = 5.factorial(4) => thus we can define factorial(5) in terms of factorial(4). In general, for a positive integer n, we can define factorial(n) to be n times factorial(n-1). This leads to what we call a recursive definition.

3 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:

4 Example I using recursion: Sum of values from 1 to N (ctd)
// This method returns the sum of 1 to num // Refer to SumApp project public int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (n-1); return result; }

5 Example I using recursion: Sum of values from 1 to N (ctd)
main sum sum(3) sum(1) sum(2) result = 1 result = 3 result = 6

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 The recursive definition contains one or more base cases, which are defined nonrecursively in terms of fixed quantities. In the case of factorial, n=0 is the base case. It also contains one or more recursive cases, which are defined by appealing to the definition of the function being implemented. We can illustrate the execution of a recursive function by means of a recursive trace.

7 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)!

8 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

9 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.

10 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) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n–1) + fibonacci(n–2)

11 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

12 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 ) 3 2 1 return call * = 6 24 final answer Each entry of the trace corresponds to a recursive call. Each new recursive function call is indicated by an arrow to the newly called function. When the function returns, an arrow showing this return is drawn and the return value may be indicated with this arrow.

13 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

14 Example IV using recursion: Binary Search (cont’d)
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 pool middle A

15 Binary search recursion: pseudo-code
// Refer to BinarySearchApp project Boolean BS(A, key, start, end) mid = (start+end)/2 if(A[mid] == key) return true else if(end <= start) return false if (A[mid] > key) return BS(A, key, start, mid-1) return BS(A, key, mid+1, end)

16 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

17 Original Configuration
Towers of Hanoi Original Configuration Move 1 Move 2 Move 3

18 Towers of Hanoi Move 4 Move 5 Move 6 Move 7 (done)


Download ppt "Recursion."

Similar presentations


Ads by Google