1 / 18

Recursion

Recursion. Canonical example: factorial. Recursion When a method calls itself Classical example – the factorial function n! = 1 · 2 · 3 · ··· · (n-1) · n Recursive definition. Example I using recursion: Sum of values from 1 to N. Problem

evita
Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  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 intsum (intnum) { int result; if (num == 1) result = 1; else result = num + sum (n-1); return result; }

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

  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

  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(intcounter = 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 • BigIntegerand BigDecimalexplicitly 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. • BigIntegerconstant • ONErepresents the integer value 1. • ZEROrepresents 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) = 0fibonacci(1) = 1fibonacci(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 thereturn type of • The fibonacci method • BigInteger methods multiply and subtract • implement multiplication and subtraction. • Refer to FibonacciApp project

  12. return 4 * 6 = 24 final answer call recursiveFactorial ( 4 ) return 3 * 2 = 6 call recursiveFactorial ( 3 ) return 2 * 1 = 2 call recursiveFactorial ( 2 ) return 1 * 1 = 1 call recursiveFactorial ( 1 ) return 1 call recursiveFactorial ( 0 ) 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:

  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) • 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 end: index of 1st element in search pool start: 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 else if (A[mid] > key) return BS(A, key, start, mid-1) else 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 Move 1 Move 2 Move 3 Towers of Hanoi

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

More Related