You are on page 1of 61

RADHARAMANENGINEERINGCOLLEGEBH

OPAL

DEPARTMENTOFCOMPUTERSCIENCEANDE
NGINEERING

LABMANUAL
AnalysisandDesignofAlgorithmsC
S-404
ListofExperiments

S# LabAssignment Page
Number

1 WriteaprogramforIterativeandRecursiveBinarySearch

2 WriteaprogramforMergeSort

3 WriteaprogramforQuickSort

4 WriteaprogramforStrassen’sMatrixMultiplication

5 WriteaprogramforOptimalMergePatterns

6 WriteaprogramforHuffmanCoding

7 WriteaprogramforMinimumSpanningTreesusingKruskal’salgorithm

8 WriteaprogramforMinimumSpanningTreesusingPrim’salgorithm

9 WriteaprogramforSingleSourceShortestPath

10 Writeaprogramforfloyd-Warshallalgorithm

11 WriteaprogramforTravelingsalesmanproblem

12 WriteaprogramforHamiltonianProblem
LABEXPERIMENT-1

AIM

WriteaProgramforIterativeandRecursiveBinarySearch

INTRODUCTION

Search a sorted array by repeatedly dividing the search interval in half. Begin with an
intervalcovering the whole array. If the value of the search key is less than the item in the middle
of theinterval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedlycheckuntil the value is foundor the interval is empty.

ALGORITHM

ITERATIVEALGORITHM
RECURSIVEALGORITHM

PROGRAM
for(i=0;i<n;i+
+)scanf("%d",&a[i]);for(i=0;i<n-
1;i++)

for(j=0;j<n-i-1;j++)
{

if(a[j+1]<a[j])
{
temp=a[j];a[j]
=a[j+1];a[j+1]
=temp;

}
}

printf("the sorted numbers


are:?");for(i=0;i<n;i+
+)printf("%4d",a[i]);

beg=a[0];

end=a[9];mid=(be
g+end)/2;

printf("\nenter the number to be


searched:?");scanf("%d",&target);

while(beg<=end&&a[mid]!=target)
{
if(target<a[mid])end=mid-
1;elsebeg=mid+1;mid=(beg+end)/
2;}if(a[mid]==target)

printf("\nthe number is found at position %2d",mid);


}
else
{
printf("\nthe number is not found:");
}
getch();
}
SAMPLE OUTPUT

QUESTIONS

What are recursive algorithms?

What are iterative algorithms?

Compare recursive versus iterative algorithms.

What is the time complexity of binary search algorithm?

What is the space complexity of binary search algorithm?


LABEXPERIMENT-2

AIM

WriteaprogramforMergeSort

INTRODUCTION

Divide and Conquer


Divideandconquerisanimportantalgorithmdesignparadigmbasedonmultibranchedrecursion. A
divide and conquer algorithm works by recursively breaking down a problem intotwo or more
sub-problems of the same (or related) type, until these become simple enough to besolved
directly. The solutions to the sub-problems are then combined to give a solution to
theoriginalproblem.Thistechniqueisthebasis of efficient algorithms for all kinds of problems,such
as sorting (e.g., quicksort, merge sort), multiplying large numbers (e.g Karatsuba),
syntacticanalysis(e.g.,top-down parsers),andcomputing thediscreteFourier transform(FFTs).

Mergesort
Merge sort is an O(n log n) comparison-based sorting algorithm. In most implementations it
isstable, meaning that it preserves the input order of equal elements in the sorted output. It is
anexample of the divide and conquer algorithmic paradigm

ALGORITHM

Steps:
If the list is of length 0 or 1, then it is already sorted. Otherwise
Divide the unsorted list into two sublists of about half the size
Sorteachsublist recursivelyby re-applyingmergesort.
Mergethetwo sublistsback intoone sortedlist
PROGRAM
//MergeSort
int
h,i,j,b[20],k;h=l
ow;

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];
}
void main()
SAMPLE OUTPUT

QUESTIONS

LAB EXERCISE- 3

AIM

WriteaprogramforQuickSort
INTRODUCTION

Quicksort is a recursive sorting algorithm following the 'divide et impera' scheme. it takes
anelement (token) of the list that is to sort and transfers every element that smaller on the one
sideand everything that is bigger on the other. for the whole list, the algorithm is used on the
twoparts again until the list is sorted.

ALGORITHM

PROGRAM
int
partition(int,int);voi
d main()

int
i,j,p,q,n,m;clr
scr();

cout<<"Enter the elents to


sort";cin>>q;

cout<<"Enter ("<<q<<") Numbers"


<<endl;for(i=0;i<q;i++)

{
cin>>a[i];
}p=0;q=
q-
1;n=p;m=q;qui
cksort(n,m);

cout<<"Sorted Numbers
Are"<<endl;for(i=0;i<q+1;i++)

{
cout<<a[i];
}
getch();
}
void quicksort(int top, int bottom)
{
// top = subscript of beginning of array
// bottom = subscript of end of array

int middle;
if (top < bottom)
{
middle = partition(top,
bottom);quicksort(top,middle);//sortfirsts
ection

quicksort(middle+1, bottom); // sort second section

}
SAMPLE OUTPUT
QUESTIONS
LAB EXERCISE- 4

AIM

WriteaprogramforStrassen’sMatrixMultiplication

INTRODUCTION

ALGORITHM

PROGRAM
SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE- 5

AIM

WriteaprogramforOptimalMergePatterns

INTRODUCTION

Wewanttomergesomesortedfileswherethenumberofrecordsare
{12,34,56,73,24,11,34,56,78,91,34,91,45}.Whatistheoptimalwaytomergethem?

ALGORITHM:
PROGRAM
while(i<n)
{k+
+;

if((c[k-1]+a[i])<=(a[i]+a[i+1]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=a[i]
+a[i+1];i=i+2;w
hile(i<n)

{ k++;

if((c[k-1]+a[i])<=(c[k-2]+a[i]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=c[k-2]+a[i];
}i++;
}
}i++;
}k+
+;

c[k]=c[k-1]+c[k-2];

cout<<"\n\nThe optimal sum are as follows......\n\n";


for(k=0;k<n-1;k++)
{
cout<<c[k]<<"\t";
}l=
0;

for(k=0;k<n-1;k++)
{
l=l+c[k];
}
cout<<"\n\nThe external path length is........"<<l;
getch();
PROGRAM

SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE- 6

AIM

WriteaprogramforHuffmanCoding

INTRODUCTION:

Givenasetofmessageswithprobabilitiesp1p2pn,theHuffmancodetreeisconstructedbyrecursivel
y combining subtrees:

Begin with n trees, each consists of a single node corresponding to one message word,
withthe weight of pi

Repeat until there is only one tree

_ pick two subtrees with smallest weights


_ combine them by adding a new node as root, and make the two trees its children.The weight
ofthe new tree is the sum of the weight of two subtrees

Witha heap,each stepof combiningtree takesO(log n)time, andthe totaltime isO(n logn).

ALGORITHM
PROGRAM

#include<iostream.h>
#include<string.h>#i
nclude<math.h>#incl
ude<stdlib.h>#includ
e<conio.h>

struct tree
{
char
a[20];int s;

struct tree *left,*right;


}*root=NULL,*tt[20]={NULL},*temp,*temp2,*t2,*ri,*le;
struct pqu

{
int
info;char
a[20];struct
pqu *ptr;

}*front=NULL,*t,*par,*t1,*p1,*p2;s
truct pqu* fp(int info)

{
struct pqu *p=NULL;
for(t1=front;t1->info<info&&t1!=NULL;t1=t1->ptr)
{
p=t1;
}
return (p);
}
void enqu(char a[20],int p)
{
t=(struct pqu*)malloc(sizeof(struct
pqu));strcpy(t->a,a);

t->info=p;
t->ptr=NULL;
if(front==NULL)
{
front=t;
}
else
{
par=fp(p);if(par
==NULL)

{
t-
>ptr=front;fr
ont=t;

else
{
t->ptr=par-
>ptr;par->ptr=t;

}
}

struct pqu* dequ()


{
t1=front;front=fr
ont->ptr;return
t1;

void info(char c[2])


{
int
m=0,i;temp
2=root;

while(strcmp(c,temp2->a)!=0)

{
t2=temp2-
>left;for(i=0;i<strlen(t2-
>a);i++)

{
if(t2->a[i]==c[0])
{
temp2=temp2->left;
m=1;
cout<<"0";
break;

}
}
if(m!=1)
{
temp2=temp2-
>right;cout<<1;

}m=
0;

}
}

void insert()
{
char a1[20],b1[20],v1[20];
int
i,j,z=0,l;while(front!
=NULL)

{
p1=dequ();strcpy
(a1,p1->a);l=p1-
>info;p2=dequ();
if(p2==NULL)

break;strcpy(b1,
p2-
>a);strcpy(v1,a1)
;
temp=(struct tree*)malloc(sizeof(struct
tree));strcpy(temp->a,strcat(v1,b1));

temp->s=l+p2-
>info;temp-
>left=NULL;temp-
>right=NULL;temp2
=temp;root=temp;for
(i=0;i<z;)

{
if(strcmp(tt[i]->a,a1)==0)
{
temp-
>left=tt[i];for(l=
i;l<z;l++)

tt[l]=tt[l+1];
}i=
0;

continue;

}
else if(strcmp(tt[i]->a,b1)==0)
{
temp-
>right=tt[i];for(l=
i;l<z;l++)

{
tt[l]=tt[l+1];
}
i=0;
continue;
}i+
+;

}
if(temp->left==NULL)
{
le=(struct tree*)malloc(sizeof(struct
tree));strcpy(le->a,a1);

le-
>left=NULL;le-
>right=NULL;te
mp2->left=le;
}
if(temp->right==NULL)
{
ri=(structtree*)malloc(sizeof(structtree));s
trcpy(ri->a,b1);

ri-
>left=NULL;ri-
>right=NULL;te
mp2->right=ri;

}
if(front!
=NULL)enqu(temp2-
>a,temp2->s);tt[z+
+]=temp2;

}
}
void disp(struct tree *rt)
{
if(rt!=NULL)
{
disp(rt-
>left);cout<<"<<
rt->a";disp(rt-
>right);

}
}
void main()
{
textmode(MONO);
inti=0,g,h,p,y,n;

char m[20],b[20]
[2],re;while(1)

{
clrscr();

cout<<"=========================";
cout<<" HUFFMAN CODING";

cout<<"=================================";
c
out<<"Enter the total no of characters :
";cin>>n;

for(i=0;i<n;i++)
{
cout<<"Enter the character :
";cin>>m;

strcpy(b[i],m);
cout<<"Enter frequency for "<<m<<" :
";cin>>g;

enqu(m,g);
}
PROGRAM

SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE 7

AIM

WriteaprogramforKNAPSACKProblem

INTRODUCTION

The knapsack problem orrucksack problem isa problem in combinatorialoptimization:Given a


set of items, each with a weight and a value, determine the number of each item toinclude in a
collection so that the total weight is less than a given limit and the total value is
aslargeaspossible.Itderivesitsnamefromtheproblemfacedbysomeonewhoisconstrainedbyafixed-
size knapsack and must fill it with the most useful items.

Theproblemoftenarisesinresourceallocationwithfinancialconstraints.Asimilarproblemalsoappearsin
combinatory,complexitytheory,cryptographyandappliedmathematics.

In the following, we have n kinds of items, 1 through n. Each kind of item i has a value vi and
aweightwi.Weusuallyassumethatallvaluesandweightsarenonnegative.Themaximumweightthat we
can carry in the bag is W.

Themostcommonformulationoftheproblemisthe0-1knapsackproblem,whichrestrictsthenumber
xi of copies of each kind of item to zero or one. Mathematically the 0-1-knapsackproblem can be
formulated as:


maximize

subject to
The bounded knapsack problem restricts the number xi of copies of each kind of item to
amaximumintegervalueci.Mathematicallytheboundedknapsackproblemcanbeformulatedas:


maximize

subject to
Theunboundedknapsackproblemplacesnoupperboundonthenumberofcopiesofeachkind of
item.

Of particular interest is the special case of the problem with these properties:

it is a decision problem,

it is a 0-1 problem,

for each kindof item, the weight equals the value: wi = vi.
Notice that in this special case, the problem is equivalent to this: given a set of
nonnegativeintegers,doesanysubsetofitadduptoexactlyW?
Or,ifnegativeweightsareallowedandWischosen to be zero, the problem is: given a set of integers,
does any subset add up to exactly 0?

This special case is called the subset sum problem. In the field of cryptography the term
knapsackproblemisoften usedtorefer specificallytothe subsetsumproblem.
If multiple knapsacks are allowed, the problem is better thought of as the bin packing problem.

ALGORITHM

PROGRAM
cin>>m;u=m;

for(i=0;i<5;i++)

{
x[i]=0.0;
}
for(i=0;i<5;i++)
{
d[i]=p[i]/w[i];
}
for( i=0;i<4;i++)
{
for( j=0;j<4;j++)
{
if(d[j]<d[j+1])
{

}
swap(d,j);
swap(p,j);
swap(w,j);
}
}
for(i=0;i<5;i++)
{
if(w[i]>u)
{
x[i]=u/w[i];
}
else

{ x[i]=1;
u=u-w[i];}

for(i=0;i<5;i++)
{
cout<<x[i]<<" ";
}
for(i=0;i<5;i++)
PROGRAM

SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE 8

AIM

ImplementPrim’salgorithmtofindminimumcostspanningtree

INTRODUCTION

Prim's algorithm is an algorithm in graph theory that finds a minimum spanning tree for
aconnected weighted graph. This means it finds a subset of the edges that forms a tree
thatincludes every vertex, where the total weight of all the edges in the tree is minimized.
Thealgorithmwasdiscoveredin1930bymathematicianVojtěchJarníkandlaterindependentlybyco
mputer scientist Robert C. Prim in 1957 and rediscovered by Edsger Dijkstra in 1959.

ThereforeitissometimescalledtheDJPalgorithm,theJarníkalgorithm,orthePrim-Jarníkalgorithm

ALGORITHM

PSEUDO CODE
PROGRAM
for (i=0; i<nodes ; i++) // Initialize the selected vertices
listselect[i] = 0;

cout<<"\n\nTheMinimalSpanningTreeIs:\
n";select[0] = 1;

for (k=1 ; k<=nodes-1 ; k++)

{
min_dist=INFINITY;
for (i=0; i<=nodes-1 ; i++) // Select an edge such that one vertex is
{ // selected and other is not and the edge
for (j=0; j<=nodes-1 ; j++) // has the least weight.
{

select[j])))
if(G[i][j] && ((select[i] && !select[j])||(!select[i]&&

{
if (G[i][j] < min_dist)//obtained edge with minimum wt
{
min_dist = G[i][j];v1 = i;

v2 = j; //picking up those vertices


}
}
}
}
cout<<"\n Edge ("<<v1<<" "<<v2<<")and weight
="<<min_dist<<endl;select[v1] = select[v2] = 1;

total =total+min_dist;
}
cout<<"\n\n\tTotalPathLengthIs="<<total<<endl;
}

void main()
{
int nodes;
int v1, v2, length, i, j, n;

clrscr();
cout<<"\n\t Prim'SAlgorithm\n";
SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE 9

AIM

ImplementDijkstra’salgorithm.

Introduction

Dijkstra’salgorithm.isagraphsearchalgorithmthatsolvesthesingle-sourceshortestpathproblem for a
graph with non negative edge path costs, outputting a shortest path tree. Thisalgorithm is often
used in routing.

For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost
(i.e.the shortest path) between that vertex and every other vertex. It can also be used for finding
costsof shortest paths from a single vertex to a single destination vertex by stopping the
algorithmonce the shortest path to the destination vertex has been determined. For example, if
the verticesof the graph represent cities and edge path costs represent driving distances between
pairs ofcities connected by a direct road, Dijkstra's algorithm can be used to find the shortest
routebetween one city and all other cities. As a result, the shortest path first is widely used in
networkrouting protocols, most notably IS-IS and OSPF (Open Shortest Path First). Algorithm:
Let's callthenodeweare starting with an initial node. Let a distance of a node X be the distance
fromthe initial node to it.

ALGORITHM
Dijkstra's algorithm can be implemented more efficiently by storing the graph in the form
ofadjacency lists and using a binary heap, pairing heap, or Fibonacci heap as a priority queue
toimplement the Extract-Min function efficiently. With a binary heap, the algorithm
requiresO((|E|+|V|) log |V|) time

PROGRAM
void Graph::read()
{
cout<<”Enter the number of vertices of the graph(should be > 0)\
n”;cin>>numOfVertices;

//Number of vertices should always greater than


zerowhile(numOfVertices<=0) {

cout<<”Enter the number of vertices of the graph(should be > 0)\


n”;cin>>numOfVertices;

}
//Read the adjacency matrix for the graph with +ve
weightscout<<”Enter the adjacency matrix for the graph\
n”;cout<<”To enter infinity enter
“<<INFINITY<<endl;for(inti=0;i<numOfVertices;i++){

cout<<”Enter the (+ve)weights for the row


“<<i<<endl;for(int j=0;j<numOfVertices;j++)
{cin>>adjMatrix[i][j];

while(adjMatrix[i][j]<0) {

cout<<”Weightsshouldbe+ve.Entertheweightagain\
n”;cin>>adjMatrix[i][j];

}
}
//read the source node from which the shortest paths to other nodes has to be
foundcout<<”Enter the source vertex\n”;

cin>>source;

while((source<0)&&(source>numOfVertices-1)){
cout<<”Sourcevertexshouldbebetween0and“<<numOfVertices-
1<<endl;cout<<”Enter the source vertex again\n”;

cin>>source;

}
}
void Graph::initialize()
{
for(int i=0;i<numOfVertices;i++)
{mark[i] = false;

predecessor[i] = -
1;distance[i]=INFINIT
Y;

}
distance[
/source]

= 0;
}
int Graph::getClosestUnmarkedNode()
{
intminDistance=INFINITY;i
nt closestUnmarkedNode;

for(inti=0;i<numOfVertices;i++){
if((!mark[i]) && ( minDistance >= distance[i]))
{minDistance=distance[i];closestUnmarkedNode
= i;

}
return closestUnmarkedNode;
}
void Graph::dijkstra()
{
initialize();
intminDistance=INFINITY;i
ntclosestUnmarkedNode;int
count = 0;

while(count < numOfVertices)


{closestUnmarkedNode =
getClosestUnmarkedNode();mark[closestUnmarkedN
ode] = true;

for(inti=0;i<numOfVertices;i++){
if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {
if(distance[i] > distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i])
{distance[i] = distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode]
[i];predecessor[i] = closestUnmarkedNode;

}
}
}
count++;
}
}
void Graph::printPath(int node)
{
PROGRAMSAMP

LEOUTPUT

QUESTIONS
LABEXERCISE-10

AIM

Writeaprogramforfloyd-Warshallalgorithm

ALGORITHM

PROGRAM

SAMPLE OUTPUT

QUESTIONS
LABEXERCISE-11

AIM

WriteaprogramforTravelingsalesmanproblem

ALGORITHM

PROGRAM

SAMPLE OUTPUT

QUESTIONS
LAB EXERCISE-
12

AIM

WriteaprogramforHamiltonianProblem

ALGORITHM

PROGRAM

SAMPLE OUTPUT

QUESTIONS

You might also like