AfterAcademy Tech
•
19 Dec 2019

Recursion and iteration are just two different code structures with the same end result: Execution of a set of sequential instructions repeatedly.
The emphasis of Iteration: The repeated execution of some groups of code statements in a program until a task is done.
The emphasis of recursion: Here we solve the problem via the smaller sub-problems till we reach the trivial version of the problem i.e. base case.

If recursion is usually slower then what is the technical reason for using it over iteration?
We will now see the code of following questions implemented as both recursion and iteration to help you better see the difference
Example 1: Finding nth Fibonacci number
int fib(int n)
{
if(n <= 1)
{
return n
}
return fib(n-1) + fib(n-2)
}
int fib(int n)
{
if( n <= 1 )
return n
a = 0, b = 1
for( i = 2 to n )
{
c = a + b
a = b
b = c
}
return c
}
Complexity Analysis
Critical ideas to think!
Example 2: In-order traversal of a binary tree
void inorderRecursive(Node root)
{
if( root == NULL )
return
inorderRecursive(node.left)
print(root.data)
inorderRecursive(node.right)
}
void inorderIterative(Node root)
{
Node current, pre
if (root == NULL)
return
current = root
while (current != NULL) {
if (current.left == NULL) {
print(current.data)
current = current.right
}
else
{
pre = current.left
while (pre.right != NULL && pre.right != current)
pre = pre.right
if (pre.right == NULL)
{
pre.right = current
current = current.left
}
else
{
pre.right = NULL
print(current.data)
current = current.right
}
}
}
}
Critical Ideas to think
Example 3: Insertion Sort
void insertionSortRecursive(int A[], int n)
{
if (n <= 1)
insertionSortRecursive(A, n-1)
int last = A[n-1]
int j = n-2
while (j >= 0 && A[j] > last)
{
A[j+1] = A[j]
j--
}
A[j+1] = last
}
void insertionSort(int A[], int n)
{
int i, key, j
for (i = 1 to n-1)
{
key = A[i]
j = i - 1
while (j >= 0 && A[j] > key)
{
A[j + 1] = A[j]
j = j - 1
}
A[j + 1] = key
}
Complexity Analysis
Critical ideas to think!
Happy Coding! Enjoy Algorithms!
AfterAcademy Tech
The repeated execution of some groups of code statements in a program is called iteration. We will discuss the idea of iteration in detail in this blog.

AfterAcademy Tech
Using recursion, certain problems can be solved quite easily. Several algorithms design techniques and data structures are based on recursive thinking.

AfterAcademy Tech
In this blog, we will learn the difference between SQL and MySQL. People use these terms intechangeably. But both are having different meanings.

AfterAcademy Tech
In this blog, we will learn what is RDBMS and how it is different from DBMS. People often use these words intechangeably. But there is a difference between these two terms. So, let's learn how.
