1. Recursion
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
2. Recursion - Definition
Recursion means "defining a problem in terms of itself".
For example, the Fibonacci sequence is defined as: F(i) = F(i-1) + F(i-2)
Recursion is the process of defining a problem (or the solution to a problem) in
terms of (a simpler version of) itself.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
3. Recursive Function - Definition
A function which calls itself again and again directly or indirectly is defined as recursive function.
Classifications
1. Direct Recursive Function
If the function is called directly again
and again then it comes under the
Direct Recursive Function category
Sample Format:
Fun()
{
………..
Fun();
}
2. Indirect Recursive Function
If the function is called indirectly again and again then
it comes under the Indirect Recursive Function
category
Sample Format:
Fun1()
{
………
Fun2();
}
Fun2()
{
……
Fun1();
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
4. Parts of a Recursive Function
All recursive algorithms must have the following:
1. Base Case (i.e., when to stop)
2. Work toward Base Case (Converging towards the Base Case at each
recursive call)
1. Recursive Call (i.e., call the function by itself)
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
5. Problems: Recursion can be Implemented
Example 1
Find Factorial of a given number n?
n! = n * (n-1) * (n-2) * ... 2 * 1
n! = n * [(n-1) * (n-2) * ... 2 * 1]
n! = n * (n-1)!
Base Case for factorial recursive function is
0! = 1 or 1!=1
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
7. Problems: Recursion can be Implemented
Example 2
Find Sum of first n natural numbers?
Sum(n) = n + (n-1) + (n-2) + ... 2 + 1
Sum(n) = n + [(n-1) + (n-2) + ... 2 + 1]
Sum(n) = n + Sum(n-1)
Base case for Sum of first n natural numbers is
Sum(1) = 1
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
8. Recursive Function for finding sum of first n
natural numbers
int sum(n)
{
//Base Condition
if(n==1)
{
return 1;
}
else
{
return (n + sum(n-1));
}
}
sum(4)
= 4 + sum(3)
= 4 + (3 + sum(2))
= 4 + (3 + (2 + sum(1)))
= 4 + (3 + (2 + (1)))
= 4 + (3 + (3))
= 4 + (6)
= 10
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
9. Function for finding the GCD of two numbers
int gcd(int p, int q)
{
if(p==0 && q!=0)
{
return q;
}
else
{
if(p!=0 && q==0)
{
return p;
}
}
//Base Condition
if(p==q)
{
return p;
}
else
{
if(p>q)
{
return(gcd(p-q,q));
}
else
{
return(gcd(p,q-p));
}
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
10. Find binomial coefficient value ncr = n!/((n-r)!*r!)
/* Program to find binomial co-efficient */
#include <stdio.h>
int binomial(int,int);
void main()
{
int n,r,ncr;
clrscr( );
printf(“Enter n and r valuesn“);
scanf(“%d %d”,&n,&r);
ncr=fact(n)/(fact(n-r)*fact(r));
printf(“n Binomial coefficient : %d”,ncr);
}
int fact(int n)
{
if(n==1)
return(1);
else
return(n*fact(n-1));
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
11. /* Method 2: C Program to calculate Binomial coefficient using Recursion */
#include<stdio.h>
int BC(int n, int k);
int main()
{
int n,k;
printf("Enter n and k : ");
scanf("%d%d",&n,&k);
printf("%nBinomial coefficientn",BC(n,k));
printf("%dn",BC(n,k));
return 0;
}
int BC(int n, int k)
{
if(k==0 || k==n)
return 1;
return BC(n-1,k-1) + BC(n-1,k);
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
12. Fibonacci Series
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A formal definition of the recursive function for Fibonacci sequence is as follows:
0 if (n=0)
fib(n) = 1 if (n=1)
fib(n-1) + fib (n-2) if (n>1)
Fibonacci series or Fibonacci sequence is a series of integers where each number in the series is the sum of the
two preceding numbers. But here there are two starting values that are assumed i.e. 0 and 1. So the third
term can be generated as sum of these terms 0+1=1. The fourth term is the sum of 1 and 1 and so it 2. We
can generate as many terms as we require in the series.
F0=0;
F1=1;
F2=F0+F1=1
F3=F1+F2=2
. . .
Fn = Fn-2 + Fn-1
Fibonacci series is a sequence of following numbers
0 1 1 2 3 5 8 13 21 ....
13. Recursive Function Program for generating Fibonacci Series
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci seriesn");
for ( c = 1 ; c <= n ; c++ )
{
printf("%dn", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
14. Towers of Hanoi Problem
Tower of Hanoi is a mathematical puzzle where we have three
rods(pegs) and n disks. The objective of the puzzle is to move
the entire stack to another rod(peg), obeying the following simple
rules:
1.Only one disk can be moved at a time.
2.Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
3.No disk may be placed on top of a smaller disk.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
15. Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Towers of Hanoi Problem for 3 Disks
The pattern here is : Shift 'n-1' disks from 'A' to 'B'. Shift last disk from 'A' to 'C'. Shift 'n-1' disks from 'B' to 'C'.
The pattern here is :
Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.
16. Towers of Hanoi Program for n disks
/* C program for Tower of Hanoi using Recursion */
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
17. Merge Sort Technique
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
18. Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several sub-
lists until each sublist consists of a single element and merging those sublists in a manner that results into a
sorted list.
Idea:
• Divide the unsorted list into N sublists, each containing 1 element.
• Take adjacent pairs of two singleton lists and merge them to form a list of 2 elements. N will now convert
into N/2 lists of size 2.
• Repeat the process till a single sorted list of obtained.
While comparing two sublists for merging, the first element of both lists is taken into consideration. While
sorting in ascending order, the element that is of a lesser value becomes a new element of the sorted list.
This procedure is repeated until both the smaller sublists are empty and the new combined sublist
comprises all the elements of both the sublists.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
19. Merge-sort - Example
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
20. by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
21. Merge Sort - Algorithm
MergeSort(A,low,high)
[A[0….n-1] is the input array to be sorted, low and high gives the
indices of the first and last elements of the array]
IF(low<high) THEN
mid = (low + high)/2
MergeSort(A,low,mid)
MergeSort(A, mid+1,high)
Merge(A,low,mid,high)
ENDIF
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
22. merge(A,low,mid,high)
[A[0….n-1] is the array where low give the index of the first and high gives
the index of the last element under consideration, mid gives the index of
the middle element]
[Initialize the Variables]
Step 1:
i=low
h=low
j=mid+1
23. [ Do merging process until one of the subsets get exhausted for the two sorted subsets
A[low..mid] and A[mid+1…high] after comparing the first element from each subset each time ]
Step 2:
WHILE (h<=mid and j<=high) DO
IF(A[h] <= A[j]) THEN
B[i] = A[h]
h = h+1
ELSE
B[i] = A[j]
j = j +1
ENDIF
i = i + 1
ENDWHILE
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
24. [First subset gets exhausted, add remaining elements of second subset to the resultant
set]
IF h>mid, THEN
FOR k=j to high DO
B[i] = A[k]
i=i+1
k=k+1
ENDFOR
ELSE [Second subset gets exhausted, add remaining elements of first subset to the
resultant set]
FOR k=h to mid DO
B[i] = A[k]
i=i+1
k=k+1
ENDFOR
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
25. [Copy elements from array B to A]
FOR k=low to high DO
A[k] = B[k]
k=k+1
ENDFOR
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
26. // Merge Sort - Program
#include<stdio.h>
void merge(int a[],int,int,int);
void mergesort(int a[],int ,int);
void main()
{
int a[10],n,i;
clrscr();
printf("nEnter the number of elementsn");
scanf("%d",&n);
printf("nEnter the e;lementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("nSorted elements aren");
for(i=0;i<n;i++)
printf("%dn",a[i]);
getch();
} by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
27. void mergesort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
28. void merge(int a[],int low,int mid,int high)
{
int i,j,k,c[10];
i=low;
j=mid+1;
k=0;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=a[j];
j++;
k++;
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
30. Quick Sort Technique
• Divide and Conquer Method
Procedure
• Step 1: Choose the Pivot element - First element of the given list of n
elements is considered as Pivot element
• Step 2: Remaining (n-1) elements are compared with this pivot element
to place it in appropriate position if the list of n elements were in sorted
order
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
31. Step 2: Remaining (n-1) elements are compared with this pivot element to place it in appropriate
position if the list of n elements were in sorted order
Process
We use two variable i and j.
Variable i is initialized to the index of the second element (i=1)
Variable j is initialized to the index of the last element (j=n-1)
According to Step 1 the Pivot element is the first element (pivot = A[0])
Left to Right Traversal
Pivot is compared with the elements starting from A[i] until an element whose value is greater than the pivot element is encountered. At this point, we
stop incrementing i and initiate Right to Left Traversal.
Right to Left Traversal
The variable j is decremented by comparing A[j] with the pivot until an element whose value is less than the pivot is encountered. At this point we stop
decrementing j .
Once one pair of Left to Right and Right to Left Traversals are over we compare the values of variables i and j. If i<j then swap A[i] with A[j] and continue
the process of Left to Right and Right to Left Traversals. If i>=j then we can stop this operation and swap pivot with A[j]. Then all the elements to the left
of pivot will be having lesser than the pivot and all the elements to the right of pivot will be having values greater than the pivot. Hence we can say the
pivot is placed in the correct location if the list of n elements were in sorted order.
Then we continue the process for the subset lying towards the left side of the pivot and right side of the pivot until we get single element subsets.
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
32. Quick Sort Example
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
33. Quick Sort - Algorithm
Quicksort(A[],lb,ub)
{
if(lb<ub)
{
q = partition(A,lb,ub);
Quicksort(A,lb,q);
Quicksort(A,q+1,ub);
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
34. Partition(A[],lb,ub)
{
pivot = A[lb];
i=lb;
j=ub + 1;
While true do
{
repeat i=i+1 until A[i]>pivot;
repeat j=j-1 until A[j]<pivot;
if i<j
swap(A[i],A[j]);
else
return j;
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
35. //Quicksort Program
#include<stdio.h>
void main()
{
int n,a[30],i;
clrscr();
printf("nEnter No. of elements:");
fflush(stdin);
scanf("%d",&n);
printf("nEnter %d elements",n);
for(i=0;i<n;i++)
{
fflush(stdin);
scanf("%d",&a[i]);
}
qs(a,0,n-1);
printf("nElements after sortingn");
for(i=0;i<n;i++)
{
printf("%dt",a[i]);
}
getch();
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
36. qs(int a[30],int lb,int ub)
{
int q;
if(lb<ub)
{
q=partition(a,lb,ub);
qs(a,lb,q-1);
qs(a,q+1,ub);
}
}
by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
37. partition(int a[30],int lb, int ub)
{
int pivot=a[lb],i=lb+1,j=ub,temp;
while(1)
{
while(a[i]<pivot && i<ub)
{
i++;
}
while(a[j]>pivot && j>0)
{
j--;
}
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
a[lb] = a[j];
a[j]=pivot;
return j;
}
}// End of while loop
} by Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru