Lab Manual
Lab Manual
Laboratory Manual
Algorithms
For
2nd Semester M.Sc
LABORATORY MANUAL CONTENTS
This manual is intended for the 2nd semester M.Sc students. This manual typically
contains practical/ Lab Sessions related to Algorithms covering various aspects
related to the subject for enhanced understanding.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
SUBJECT INDEX:
2 . Lab Exercises
IV. Program to implement minimum and maximum using Divide and Conquer V.
Program to implement Merge sort using Divide and Conquer
3. Quiz
1. Turn off the machine once you are done using it.
2. Student should not attempt to repair, open, tamper or interfere with any of the
computer, printing, cabling or other equipment in the laboratory.
3. Make entry in the Log Book as soon as you enter in the laboratory.
4. All the students are supposed to enter the terminal number in the log book.
5. Handle equipment with care.
12. Do not plug in external devices without scanning them for computer viruses.
Instruction for Laboratory Teachers:-
1. Submission related to whatever lab work has been completed should be done
during the next lab session.
2. Students should be instructed to start the computers. After the experiment is over,
the students must shut down the Computers and turn off the switches.
3. The promptness of submission should be encouraged by way of marking and
evaluation patterns that will benefit the sincere students.
Experiment No.1
Heap sort
Objective: To write a C program to perform Heap sort using the divide and conquer
technique
Theory: A max (min) heap is complete binary tree with the property that the value at
each node is at least as large as (as small as) the values at its children (if they exist) Call
this property the heap property.
Algorithm:
Step 1: Start the process.
Step 2: Declare the variables.
Step 3: Enter the list of elements to be sorted using the get function.
Step 4: Divide the array list into two halves the lower array list and upper array list
using the merge sort function.
Step 5: Sort the two array list.
Step 6: Combine the two sorted arrays.
Step 7: Display the sorted elements using the get() function.
Step 8: Stop the process
#include<stdio.h> void
heapsort(int[],int); void
heapify(int[],int); void
adjust(int[],int);
void main() {
int n,i,a[50];
clrscr();
printf("\nEnter the limit:");
scanf("%d",&n);
printf("\nEnter the elements:");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("\nThe Sorted Elements Are:\n");
for (i=0;i<n;i++)
printf("\n %d",a[i]);
printf("\n");
getch();
}
void heapsort(int a[],int n) {
int i,t;
heapify(a,n);
for (i=n-1;i>0;i--) {
t = a[0];
a[0] = a[i];
a[i] = t;
adjust(a,i);
}
}
void heapify(int a[],int n) {
int k,i,j,item;
for (k=1;k<n;k++) {
item = a[k];
i = k;
j = (i-1)/2;
while((i>0)&&(item>a[j])) {
a[i] = a[j];
i = j;
j = (i-1)/2;
}
a[i] = item;
}
}
void adjust(int a[],int n) {
int i,j,item; j = 0; item =
a[j]; i = 2*j+1;
while(i<=n-1) {
if(i+1 <= n-1)
if(a[i] <a[i+1])
i++;
if(item<a[i]) {
a[j] = a[i];
j = i;
i = 2*j+1;
} else
break;
}
a[j] = item;
}
OUTPUT:
Time complexities: - Though the call of Heapify requires only O(n) operations, Adjust
possibly requires O(log n) operations for each invocation. Thus the worst case time is
O(n log n).
Conclusion: Hence we have studied and executed the program for Heap sort.
Experiment No.2
Binary Search
Objective: To write a C program to perform binary search using the divide and conquer
technique.
Theory: A binary search tree is a binary tree. It may be empty. If it is not empty, then it
satisfies the following properties:
1. Every element has a key and no two elements have the same key.
2. The keys (if any) in the left sub tree are smaller than the key in the root.
3. The keys (if any) in the right sub tree are larger than the key in the root.
4. The left and right sub trees are also binary search trees.
Algorithm:
#include <stdio.h>
Void main()
{
int c, first, last, middle, n, search, array[100];
OUTPUT:
Time complexities: -For Searching the element the worst case time complexity is O(n)
and average case is O(log n).
Conclusion: Hence we have found the given element in the binary search tree.
Experiment No.3
Quick Sort
Objective: To write a C program to perform Quick sort using the divide and conquer
technique
Theory: Quick Sort divides the array according to the value of elements. It rearranges
elements of a given array A[0..n-1] to achieve its partition, where the elements before
position s are smaller than or equal to A[s] and all the elements after position s are
greater than or equal to A[s].
Algorithm:
Step 1: Start the process.
Step 2: Declare the variables.
Step 3: Enter the list of elements to be sorted using the get()function.
Step 4: Divide the array list into two halves the lower array list and upper array list
using the merge sort function.
Step 5: Sort the two array list.
Step 6: Combine the two sorted arrays.
Step 7: Display the sorted elements.
Step 8: Stop the process.
#include <stdio.h>
#include <conio.h>
void qsort(); int n;
void main()
{
int a[100],i,l,r;
clrscr();
printf("\nENTER THE SIZE OF THE ARRAY: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nENTER NUMBER-%d: ",i+1);
scanf("%d",&a[i]);
}
printf("\nTHE ARRAY ELEMENTS BEFORE SORTING: \n");
for(i=0;i<n;i++)
{
printf("%5d",a[i]);
}
l=0;
r=n-1;
qsort(a,l,r);
printf("\nTHE ARRAY ELEMENTS AFTER SORTING: \n");
for(i=0;i<n;i++) printf("%5d",a[i]); getch();
}
void qsort(int b[],int left,int right)
{
int i,j,p,tmp,finished,k;
if(right>left)
{
i=left;
j=right; p=b[left];
finished=0;
while (!finished)
{
do
{
++i;
}
while ((b[i]<=p) && (i<=right));
while ((b[j]>=p) && (j>left))
{
--j;
}
if(j<i)
finished=1;
else
{
tmp=b[i];
b[i]=b[j];
b[j]=tmp;
}
}
tmp=b[left];
b[left]=b[j]; b[j]=tmp;
qsort(b,left,j-1);
qsort(b,i,right);
}
return;
}
Output:
Time complexities: -Quick sort has an average time of O(n log n) on n elements. Its
worst case time is O(n²)
Conclusion: Thus the C program to perform Quick sort using the divide and conquer
technique has been completed successfully
Experiment No.4
Maximum and minimum
Aim:- Program to find out maximum and minimum using divide and conquer rule.
Objective: To write a C program to find out maximum and minimum using the divide
and conquer technique
Theory: The problem is to find the maximum and minimum number using the divide
and conquer method. Algorithm:
//Program to find out max and min using divide and conquer rule
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,a[100],max=0,min=1000,mid,n,max1,max2,min1,min2;
printf("enter the size of the array");
scanf("%d",&n);
printf("enter the elements of the array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
j=n-1;
int p=0;
if(p==j)
{
max=min=a[p];//wen der is only one element in array
printf("max is:%d and min is :%d",max,min);
}
else if(p==j-1)
{
if(a[p]<a[j])
{
max=a[j];
min=a[p];
}
else
{
max=a[p];
min=a[j];
}
printf("max is:%d and min is :%d",max,min);
}
else
{
mid=(int)((p+j)/2);
for(i=0;i<mid;i++)
{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
max1=max; min1=min;
printf("\nmax1 is :%d\n",max1);
printf("\n min1 is :%d\n",min1);
max=0; min=1000;
for(i=mid;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
max2=max; min2=min;
printf("\nmax2 is :%d\n",max2);
printf("\n min2 is :%d\n",min2);
if(max1<max2)
{
max=max2;
}
else
max=max1;
if(min1<min2)
{
min=min1;
}
else
{
min=min2;
}
printf("\nmaximum is:%d\n",max);
printf("\n minimun is:%d\n",min);
}
getch();
return 0;
}
OUTPUT:
Conclusion: Thus the Program to find out maximum and minimum using divide and
conquer rule has been completed successfully.
Experiment No.5
Merge Sort
Objective: To write a C program to perform merge sort using the divide and conquer
technique.
Theory: .As another example of Divide and conquer a sorting algorithm that in the worst
case its complexity is O(n log n). This algorithm is called Merge Sort. Merge sort
describes this process using recursion and a function Merge which merges two sorted
sets.
Algorithm:
#include<stdio.h> #include<conio.h>
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k; h=low;
i=low; j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
int num,i; printf("\t\t\tMERGE
SORT\n"); printf("\nEnter the total
numbers: "); scanf("%d",&num);
printf("\nEnter %d numbers: \n",num);
for(i=1;i<=num;i++)
{
scanf("%d",&a[i]);
}
merge_sort(1,num); printf("\nSORTED
ORDER: \n"); for(i=1;i<=num;i++)
printf("\t%d",a[i]);
getch();
}
OUTPUT:
Time Complexities:-
All cases have same efficiency: Θ( n log n),
Space requirement: Θ( n ) (NOT in-place)
Conclusion:- Thus the C program to perform merge sort using the divide and conquer
technique has executed successfully.
Experiment No.6
Knapsack Problem
Algorithm:
# include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0; int i, j, u;
u = capacity;
tp = tp + (x[i] * profit[i]);
int main() {
float weight[20], profit[20], capacity;
int num, i, j; float
ratio[20], temp;
printf("\nEnter the no.
of objects:- ");
scanf("%d", &num);
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
OUTPUT:
Conclusion:
Thus the C program for solving Knapsack problem has been executed successfully.
Experiment No.7
Prim’s algorithm
Objective: Write a C program to find the minimum spanning tree to implement prim’s
algorithm using greedy method
Algorithm:
// C Program to implement prim’s algorithm using greedy method
#include<stdio.h>
#include<conio.h>
int n, cost[10][10];
void prim() {
int i, j, startVertex, endVertex;
int k, nr[10], temp, minimumCost = 0, tree[10][3];
void main() {
int i, j; clrscr();
printf("\nEnter the costs of edges in matrix form :"); for (i = 0; i < n; i++) for (j = 0;
j < n; j++) {
scanf("%d", &cost[i][j]);
}
printf("\nThe matrix is : ");
for (i = 0; i < n; i++) { for (j
= 0; j < n; j++) {
printf("%d\t", cost[i][j]);
}
printf("\n");
}
prim();
getch();
}
Output:
Time Complexities:- The time required by algorithm Prim is O(n²), where n is the
number of vertices in the graph G.
Conclusion:- Thus the C program to find the minimum spanning tree using prim’s
algorithm has executed successfully.
Experiment No.8
Kruskal’s algorithm
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> int
i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int); int uni(int,int);
void main()
{
clrscr();
printf(“\n***** KRUSKAL’S ALGORITHM FOR MINIMUM SPANNING TREE (MST)
*****\n”);
printf(“\nImplementation of Kruskal’s algorithm\n”); printf(“\nEnter
the No. of Vertices\n”);
scanf(“%d”,&n);
printf(“\nEnter the Cost Adjacency Matrix\n”); for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf(“%d”,&cost*i+*j+);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf(“\n*** FINAL MST ***”);
printf(“\nThe Edges of Minimum Cost Spanning Tree are\n”); while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i; b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf(“\n%d Edge (%d,%d) = %d”,ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf(“\nMinimum Cost = %d\n”,mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
OUTPUT:
Time Complexities:- The computing time is O(|E| log |E|) where E is the edge set of
graph G.
Conclusion:- Thus the C program to find the minimum spanning tree using Kruskal’s
algorithm has executed successfully.
Experiment No.9
Graph Traversal: Breadth First Search
Objective: Write a C program to implement graph traversal using Breadth First Search
Theory:
BFS Breadth First Search is an algorithm used to search the Tree or Graph. BFS search
starts from root node then traversal into next level of graph or tree and continues, if
item found it stops otherwise it continues. The disadvantage of BFS is it requires more
memory compare to Depth First Search (DFS).
Algorithm:
//Program for graph traversal using BFS//
#include<stdio.h> #include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1; void
bfs(int v) {
for (i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r) {
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main() {
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++) for (j=1;j<=n;j++)
scanf("%d",&a[i][j]); printf("\n Enter
the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++) if(visited[i])
printf("%d\t",i); else printf("\n
Bfs is not possible"); getch();
}
OUTPUT:
Time Complexities:- Let T(n,e) and S(n,e) be the maximum time and maximum
additional space taken by algorithm BFS on any graph G with n vertices and e edges. T(n,
e) = Θ(n + e) and S(n, e) = Θ(n) if G is represented by its adjacency lists. If G is represented
by its adjacency matrix, then T(n, e) =Θ(n²) and S(n ,e) = Θ(n).
Conclusion:- Thus the C program for graph traversal using breadth first search has
executed successfully
Experiment No.10
Graph Traversal: Depth First Search
Objective: - Write a C program to implement graph traversal using Depth First Search
Theory:- DFS Depth First Search is an algorithm used to search the Tree or Graph. DFS
search starts from root node then traversal into left child node and continues, if item
found it stops otherwise it continues. The advantage of DFS is it requires less memory
compare to Breadth First Search (BFS).
Algorithm:-
// Program for graph traversal using Depth First Search//
#include<stdio.h>
#include<conio.h> int
a[20][20],reach[20],n;
void dfs(int v) { int i;
reach[v]=1; for
(i=1;i<=n;i++)
if(a[v][i] && !reach[i]) {
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main() {
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n); for (i=1;i<=n;i++) {
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1); printf("\n");
for (i=1;i<=n;i++) {
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected"); else
printf("\n Graph is not connected");
getch();
OUTPUT:
Time Complexities:- Let T(n, e) and S(n, e) be the maximum time and maximum
additional space taken by algorithm DFS for an n-vertex and e-edge graph, then S(n, e)
= Θ(n) and T(n, e) = Θ(n + e) if adjacency lists are used and T(n, e) =Θ(n²) if adjacency
matrices are used.
Conclusion:- Thus the C program for graph traversal using depth first search has
executed successfully
Experiment No.11
N Queen’s problem
Theory:- N Queen’s problem is the puzzle. Placing chess queens on a chessboard, so that
No two queens attack each other. Backtracking is used to solve the problem. The n-
queens problem consists of placing n queens on an n x n checker board in such a way
that they do not threaten each other, according to the rules of the game of chess. Every
queen on a checker square can reach the other squares that are located on the same
horizontal, vertical, and diagonal line. So there can be at most one queen at each
horizontal line, at most one queen at each vertical line, and at most one queen at each
of the 4n-2 diagonal lines. Furthermore, since we want to place as many queens as
possible, namely exactly n queens, there must be exactly one queen at each horizontal
line and at each vertical line. The concept behind backtracking algorithm which is used
to solve this problem is to successively place the queens in columns. When it is
impossible to place a queen in a column (it is on the same diagonal, row, or column as
another token), the algorithm backtracks and adjusts a preceding queen
Algorithm:-
// C Program for N queen’s problem using Backtracking //
#include<stdio.h>
#include<conio.h>
#include<math.h>
int a[30],count=0; int
place(int pos) {
int i;
for (i=1;i<pos;i++) {
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n) {
int i,j;
count++;
printf("\n\nSolution #%d:\n",count); for
(i=1;i<=n;i++) {
for (j=1;j<=n;j++) {
if(a[i]==j)
printf("Q\t"); else
printf("*\t");
}
printf("\n");
}
}
void queen(int n) {
int k=1;
a[k]=0;
while(k!=0) {
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n) {
if(k==n)
print_sol(n); else {
k++;
a[k]=0;
}
} else
k--;
}
}
void main() {
int i,n;
clrscr();
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
getch();
}
OUTPUT:
Complexity:-
The power of the set of all possible solutions of the n queen’s problem is n! and the
bounding function takes a linear amount of time to calculate, therefore the running time
of the n queens problem is O(n!).
Conclusion:- Thus the C program to solve N queen’s problem using Backtracking has
executed successfully
Experiment No.12
All Pairs shortest Path
Objective: - Write a C program to find all pairs shortest path using Floyd’s algorithm
Theory:- Floyd’s algorithm is applicable to both directed and undirected graphs provided
that they do not contain a cycle. It is convenient to record the lengths of shortest path
in an n- by- n matrix D called the distance matrix. The element dij in the ith row and jth
column of matrix indicates the shortest path from the ith vertex to jth vertex (1<=i, j<=n).
The element in the ith row and jth column of the current matrix D(k-1) is replaced by
the sum of elements in the same row i and kth column and in the same column j and the
kth column if and only if the latter sum is smaller than its current value.
Algorithm:-
Algorithm Floyd(W[1..n,1..n])
//Implements Floyd’s algorithm for the all-pairs shortest paths problem
//Input: The weight matrix W of a graph
//Output: The distance matrix of shortest paths length
{
D←W
for k←1 to n do
{
for i ← 1 to n do
{
for j ← 1 to n do
{
D[i,j] ← min (D[i, j], D[i, k]+D[k, j] )
}
}
}
return D
}
Program:
#include<stdio.h>
#include<conio.h>
void floyd(int[10][10],int);
int min(int,int); void
main()
{
int n,a[10][10],i,j; printf("Enter
the no.of nodes : ");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
floyd(a,n); getch();
}
void floyd(int a[10][10],int n)
{
int d[10][10],i,j,k;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++) d[i][j]=a[i][j];
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
printf("\nThe distance matrix is\n"); for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
int min (int a,int b)
{
if(a<b) return
a; else
return b;
}
Output:
Complexity:- The time efficiency of Floyd’s algorithm is cubic i.e. Θ (n3)
Conclusion:- Thus the C program to find shortest path using Floyd’s algorithm has
executed successfully
3.Quiz on the subject:-
1.What is an algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem. For
obtaining a required output for any legitimate input in a finite amount of time.
7.What do you mean by time complexity and space complexity of an algorithm? Time
complexity indicates how fast the algorithm runs. Space complexity deals with extra
memory it require. Time efficiency is analyzed by determining the number of repetitions
of the basic operation as a function of input size. Basic operation: the operation that
contributes most towards the running time of the algorithm The running time of an
algorithm is the function defined by the number of steps (or amount of memory)
required to solve input instances of size n.
20. What is Merge sort? and Is insertion sort better than the merge sort?
Merge sort is divide and conquer strategy that works by dividing an input array in to two
halves,sorting them recursively and then merging the two sorted halves to get the
original array sorted Insertion sort works exceedingly fast on arrays of less then 16
elements, though for large ‘n’ its computing time is O(n2).
25. Specify the algorithms used for constructing Minimum cost spanning tree. a)
Prim’s Algorithm
b) Kruskal’s Algorithm
28. Write the difference between the Greedy method and Dynamic programming.
Greedy method: 1. Only one sequence of decision is Generated 2. It does not
guarantee to give an optimal solution always.
Dynamic programming: 1. Many number of decisions are generated. 2. It definitely
gives an optimal solution always.
The marking patterns should be justifiable to the students without any ambiguity and
teacher should see that students are faced with just circumstances.
External examiner should evaluate student by checking practical performance and
conducting viva.