Recursion Apan Qasem Texas State University Spring 2011.
-
Upload
robyn-dorsey -
Category
Documents
-
view
213 -
download
0
Transcript of Recursion Apan Qasem Texas State University Spring 2011.
Recursion
Apan QasemTexas State University
Spring 2011
When to use Recursion?
• Some problems naturally fall in this category• Something defined in terms of itself
• Self-referential
• Recurrence relations or equations• Snowflake
When to use Recursion?
• Recursive data structures • Trees• Lists
• LISP and Scheme based on recursive lists
Why use recursion?
• Recursion for profit• Sometimes can get a faster a solution
• Recursion for readability• “elegant” solutions• smaller code size
The Fibonacci Sequence
• Classic example of natural recursion0 1 1 2 3 5 8 13 21
• To find nth Fibonacci need to know the previous two
Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
• Self-reference
Recursion Mechanics
• Base case• Trivial (no computation)• Can be one or more • Non-recursive way of getting out function
• Recursive case• Decompose problem as a smaller version of
itself• Result in eventually reaching the base case• Somehow be useful to solving the original
problem
Recursive Case Examples
• Parameter specifies smaller problemrecurse(n - 1);recurse(ptr->Next);
• Call may involve computation• Often value “returned” to caller
return n * factorial(n – 1)
• May have multiple calls
walk(node->leftChild);walk(node->rightChild);
Base Case Examples
• Exact condition if (n == 0) return 1;
• Rangeif (n < 2)
return 1;if (n > 0)
return 1;
• Otherif (ptr == NULL) return;
Towers of Hanoi
Move all rings from peg A to peg COnly one disc may be moved at a time.A disc can be placed either on empty peg or on top of a larger disc