Recursion1.8

# Recursion1.8 - This can lead to simple, elegant code. •...

This preview shows pages 1–5. Sign up to view the full content.

Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 41 - Tower of Hanoi 2 recursive calls!

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 42 - Tower of Hanoi Time: T(1) = 1, T(n) = 2(2T(n-2)) 4(2T(n-3)) 2T(n-1) 4T(n-2) 8T(n-3) 2 i T(n-i) 2 n 1 + 2T(n-1)
Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 43 - Binary Recursion: Summary Binary recursion spawns an exponential number of recursive calls. If the inputs are only declining arithmetically (e.g., n-1, n-2, ) the result will be an exponential running time. In order to use binary recursion, the input must be declining geometrically (e.g., n/2, n/4, ).

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 44 - The Overhead Costs of Recursion Many problems are naturally defined recursively.
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: This can lead to simple, elegant code. • However, recursive solutions entail a cost in time and memory : each recursive call requires that the current process state (variables, program counter) be pushed onto the system stack, and popped once the recursion unwinds. • This typically affects the running time constants , but not the asymptotic time complexity (e.g., O(n), O(n 2 ) etc.) • Thus recursive solutions may still be preferred unless there are very strict time/memory constraints. Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 45 - The “Curse” in Recursion: Errors to Avoid // recursive factorial function public static int recursiveFactorial( int n) { return n * recursiveFactorial ( n- 1 ); } • There must be a base condition: the recursion must ground out!...
View Full Document

## This note was uploaded on 02/14/2012 for the course CSE 2011Z taught by Professor Elder during the Fall '11 term at York University.

### Page1 / 5

Recursion1.8 - This can lead to simple, elegant code. •...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online