Recursion
- This is a programming technique
- I should have covered this in 230, but ...
- A recursive function is a function that calls itself.
- Sometimes we do this just for algorithm development
- Other times, it is for implementation.
- Our goal is to understand recursion and the cost of recursion.
- First some guidance
- To be successful a recursive algorithm or function must
- Have a base case where recursion stops.
- Have a recursive call, where the function calls itself.
- Make progress towards a base case.
- When doing a recursive design the following is true
- Solve part of the problem then use recursion to solve the rest.
- Or, I could do this if I only had my current routine implemented to solve this sub case.
- A first easy problem computing n!
- The mathematical definition for n! is sometimes given as
- This is only defined for positive integer n.
- $$
n! = \left\{
\begin{array}{lr}
n*(n-1)! & n > 1\\
1 & n =0,1 \\
\end{array}
\right.
$$
- Note this matches both cases above.
- The base case is when n =0 or 1, the answer is 1.
- The recursive case is n * (n-1)!
- Progress is n-1 which gets us closer to 0 or 1.
- And I could find n! if I just had a way to find (n-1)!
- The implementation
- Trace this.
- Another easy problem is integer power. ($a^b$) where b is an integer
- Can you give a recursive definition?
- Can you give a recursive function?
- How does this work?
- Each time a function is called, a activation record or frame is placed on the stack.
- In recursion this happens.
- This means, there is a unique copy of each local variable, paramter, and other information.
- This is slower (a hand full of instructions) than a loop.
- And it takes more memroy.
- Let's look at a classical recursive algorithms
- Binary Search
- I know you did an iterative version of this.
- What is the non-recursive algorithm?
- What recursive algorithm can we build?
- What would the recursive case be? (This has two)
- What wouuld the base case be? (This has two).
- Linked list functions are naturally recursive.
- Design a function to print a linked list.
- Design a function to copy a linked list.
- Flood Fill is natural, multi recursive function.
- We will introduce many recursive algorithms in 385.