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
- Each successive recursive call should bring you closer to a
situation in which the answer is known.
- A case for which the answer is known (and can be expressed without
recursion) is called a base case.
- 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
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
- Base-Case Question: Is there
a nonrecursive way out of the function?
- Smaller-Caller Question: Does
each recursive function call involve a smaller case of the original
problem leading to the base case?
- General-Case Question: Assuming
each recursive call works correctly, does the whole function work
correctly?
|
Use Recursion when....
- The depth of recursive calls is relatively “shallow” compared
to the size of the problem.
- The recursive version does about the same amount of work as
the nonrecursive version.
- The recursive version is shorter and simpler than the nonrecursive
solution.
|