Recursion

Recursive call A method call in which the method being called is the same as the one making the call
  • Direct recursion Recursion in which a method directly calls itself

    Indirect recursion Recursion in which a chain of two or more method calls returns to the method that originated the chain

Guidelines

  • Recursive solutions can be less efficient than iterative solutions.
  • Problems cand lend themselves to simple(r), elegant, recursive solutions.
  • Be carefull about having ending conditions...avoid making an infinite sequence of function calls (infinite recursion).

Definition of a Recursive Algorithm

  • A solution that is expressed in terms of (a) smaller instances of itself and (b) a base case

  • Base case: The case for which the solution can be stated nonrecursively
  • General (recursive) case: The case for which the solution is expressed in terms of a smaller version of itself

Designing a Recursive Algorithm

  1. Each successive recursive call should bring you closer to a situation in which the answer is known.
  2. A case for which the answer is known (and can be expressed without recursion) is called a base case.
  3. Each recursive algorithm must have at least one base case, as well as the general (recursive) case

    if (some condition for which answer is known)
             // base case solution statement

    else
            // general case recursive function call

Examples

n factorial

power of

searching a list

reverse printing a sorted linked list

binary search of sorted array

Question: are these example less efficient or more as recursive compared to iterative implementations? are they easier to understand as recursive or iterative?

Verifying Recursive Algorithms

  1. Base-Case Question: Is there a nonrecursive way out of the function?

  2. Smaller-Caller Question: Does each recursive function call involve a smaller case of the original problem leading to the base case?

  3. General-Case Question: Assuming each recursive call works correctly, does the whole function work correctly?

Use Recursion when....

  1. The depth of recursive calls is relatively “shallow” compared to the size of the problem.
  2. The recursive version does about the same amount of work as the nonrecursive version.
  3. The recursive version is shorter and simpler than the nonrecursive solution.

 

© Lynne Grewe