Recursion
Last updated
Last updated
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function.
Recursive algorithm is essential to divide and conquer paradigm, whereby the idea is to divide bigger problems into smaller subproblems and the subproblem is some constant fraction of the original problem.
The way recursion works is by solving the smaller subproblems individually and then aggregating the results to return the final solution.
So what happens if you keep calling functions that are nested inside each other?
When this happens, it’s called a stack overflow.
And that is one of the challenges you need to overcome when it comes to recursion and recursive algorithms.
In order to prevent stack overflow bugs, you must have a base case where the function stops making new recursive calls.
If there is no base case then the function calls will never stop and eventually a stack overflow will occur.
Here is an example of a recursive function with a base case.
The base case is when the counter becomes bigger than 3.
When you run this program, the output will look like this:
This program does not have a stack overflow error because once the counter is set to 4, the if statement’s condition will be True and the function will return ‘done!’, and then the rest of the calls will also return ‘done!’ in turn.
Example 1: Factorial
Recursion Good at 😀:
DRY
Readability
Recursion Bad at 😒:
Large Stack
Every time you are using a tree or converting Something into a tree, consider Recursion.
1 . Divided into a number of subproblems that are smaller instances of the same problem.
Each instance of the subproblem is identical in nature.
The solutions of each subproblem can be combined to solve the problem at hand.
Recursion | Iteration |
---|---|
Recursion uses the selection structure.
Iteration uses the repetition structure.
Infinite recursion occurs if the step in recursion doesn't reduce the problem to a smaller problem. It also becomes infinite recursion if it doesn't convert on a specific condition. This specific condition is known as the base case.
An infinite loop occurs when the condition in the loop doesn't become False ever.
The system crashes when infinite recursion is encountered.
Iteration uses the CPU cycles again and again when an infinite loop occurs.
Recursion terminates when the base case is met.
Iteration terminates when the condition in the loop fails.
Recursion is slower than iteration since it has the overhead of maintaining and updating the stack.
Iteration is quick in comparison to recursion. It doesn't utilize the stack.
Recursion uses more memory in comparison to iteration.
Iteration uses less memory in comparison to recursion.
Recursion reduces the size of the code.
Iteration increases the size of the code.