Recursion Apan Qasem Texas State University Spring 2011.

9
Recursion Apan Qasem Texas State University Spring 2011

Transcript of Recursion Apan Qasem Texas State University Spring 2011.

Page 1: Recursion Apan Qasem Texas State University Spring 2011.

Recursion

Apan QasemTexas State University

Spring 2011

Page 2: Recursion Apan Qasem Texas 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

Page 3: Recursion Apan Qasem Texas State University Spring 2011.

When to use Recursion?

• Recursive data structures • Trees• Lists

• LISP and Scheme based on recursive lists

Page 4: Recursion Apan Qasem Texas State University Spring 2011.

Why use recursion?

• Recursion for profit• Sometimes can get a faster a solution

• Recursion for readability• “elegant” solutions• smaller code size

Page 5: Recursion Apan Qasem Texas State University Spring 2011.

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

Page 6: Recursion Apan Qasem Texas State University Spring 2011.

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

Page 7: Recursion Apan Qasem Texas State University Spring 2011.

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

Page 8: Recursion Apan Qasem Texas State University Spring 2011.

Base Case Examples

• Exact condition if (n == 0) return 1;

• Rangeif (n < 2)

return 1;if (n > 0)

return 1;

• Otherif (ptr == NULL) return;

Page 9: Recursion Apan Qasem Texas State University Spring 2011.

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