Data Structures UNIT-1: Recursion: Introduction, Format of Recursive Functions, Recursion vs. Iteration, Examples
Data Structures UNIT-1: Recursion: Introduction, Format of Recursive Functions, Recursion vs. Iteration, Examples
UNIT-1
Calls factorial(2)
Returns 2
factorial (2) =2*factorial (1) factorial (3) =3*2=6
Calls factorial(1)
Returns 1
factorial (1) =1*factorial (0) factorial (2)
=2*1=2
Calls factorial(0)
1
Differences between recursive and iterative methods
Recursive method Iterative method
Reduces the code Length of the code is more
Speed of recursive methods are Faster
slow
terminated when it reaches base terminated when the condition is
condition false
Each recursive call requires extra does not require any extra space
space to execute. Stack memory
is required
If recursion goes into infinite , the Goes to infinite loop
program runs out of memory and
results in stack overflow
solution to some problems are solution to problem may not
easier with recursion always easy
Examples of recursion
1. Factorial of a number
2. Fibonacci series
3. Tree traversals- Preorder, Inorder, Postorder.
4. Binary search
5. Merge sort
6. Quick sort
7. Towers of Hanoi
8. Divide and conquer problems
9. Dynamic programming