Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Apan Qasem Texas State University Spring 2011.

Similar presentations


Presentation on theme: "Recursion Apan Qasem Texas State University Spring 2011."— Presentation transcript:

1 Recursion Apan Qasem Texas State University Spring 2011

2 When to use Recursion? Some problems naturally fall in this category Something defined in terms of itself Self-referential Recurrence relations or equations Snowflake

3 When to use Recursion? Recursive data structures Trees Lists LISP and Scheme based on recursive lists

4 Why use recursion? Recursion for profit Sometimes can get a faster a solution Recursion for readability “elegant” solutions smaller code size

5 The Fibonacci Sequence Classic example of natural recursion 0 1 1 2 3 5 8 13 21 To find n th Fibonacci need to know the previous two Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2) Self-reference

6 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

7 Recursive Case Examples Parameter specifies smaller problem recurse(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);

8 Base Case Examples Exact condition if (n == 0) return 1; Range if (n < 2) return 1; if (n > 0) return 1; Other if (ptr == NULL) return;

9 Towers of Hanoi Move all rings from peg A to peg C Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc


Download ppt "Recursion Apan Qasem Texas State University Spring 2011."

Similar presentations


Ads by Google