0% found this document useful (0 votes)
7 views72 pages

Daa Lab

The document describes a C++ program to perform merge sort. It contains the algorithm, coding and outputs of the program to sort an array using merge sort. It divides the array, recursively sorts the sub-arrays and merges the sorted sub-arrays.

Uploaded by

Moshika Vetrivel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views72 pages

Daa Lab

The document describes a C++ program to perform merge sort. It contains the algorithm, coding and outputs of the program to sort an array using merge sort. It divides the array, recursively sorts the sub-arrays and merges the sorted sub-arrays.

Uploaded by

Moshika Vetrivel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

LIST OF EXPERIMENTS

SNO EXPEIMENTS PAGE NO


DIVIDE AND CONQUER
1 Binary search 2
1(a) Iterative binary search 2
1(b) Recursive binary search 7
2 Merge sort 12
3 Quick sort 18
GREEDY METHOD
4 Prim’s algorithm 23
5 Kruskal’s algorithm 30
6 Single source shortest path 36
DYNAMIC PROGRAMMING
7 All pair shortest path 41
8 Optimal binary search tree 46
BACKTRACKING
9 N Queens problem 52
10 Sum of subsets 57
11 Graph coloring 62
12 Hamiltonian cycle 67

CSBS DEPT / ALGORITHMS LAB (P41)


Page 1
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:1(a)
DIVIDE AND CONQUER
BINARY SEARCH ITERATIVE

AIM:

To write a C++ program to search an element using binary search.

ALGORITHM:

1. Start the program


2. Declare mid,low,high,n,x and array in integer type.
3. Declare void get(), int search and void complex() functions in public mode.
4. Get the values in void get() function.
5. And perform the binary search int search(int[ ],int,int) function.
6. Calculate the time and space complexity in the void complex( ) function.
7. In the main function call all the three function and display the position of the search
element.
8. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 2
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:
#include<iostream.h>
#include<conio.h>
#include<math.h>
class binary
{
public: int i,mid,low,high,n,x,a[20];
public:
void get();
int search(int [],int,int);
void complex();
};
//GETS THE INPUT
void binary::get()
{
cout<<"\nEnter the number of elements :";
cin>>n;
cout<<"\nEnter the array elements:\n";
for(i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"\nEnter search elements:\n";
cin>>x;
}
//PERFORMS SEARCH
int binary::search(int a[], int n,int xi)
{
low=1;high=n;
while(low<high)

CSBS DEPT / ALGORITHMS LAB (P41)


Page 3
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

{
mid=(low+high)/2;
if(xi<a[mid])
{
high=mid-1;
}
else if(xi>a[mid])
{
low=mid+1;
}
else if(xi==a[mid])
{
return mid;
}
}
return 0;
}

//DISPLAYS THE TIME & SPACE COMPLEXITY

void binary::complex()
{
cout<<"\n\nTime Complexity is O("<<log(n)<<")"<<"\n";
cout<<"\nSpace Complexity is O("<<n<<")";
}
void main()
{
int m;
binary b;
clrscr();

CSBS DEPT / ALGORITHMS LAB (P41)


Page 4
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

b.get();
m=b.search(b.a,b.n,b.x);
if(m==0)
cout<<"Element not found";
else
cout<<"Element found in "<<m<<"position";
b.complex();
getch();
}

OUTPUT:
CSBS DEPT / ALGORITHMS LAB (P41)
Page 5
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

RESULT:

Thus the c++ program for iterative binary search has been executed successfully.

Ex.No:1(b)

CSBS DEPT / ALGORITHMS LAB (P41)


Page 6
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

BINARY SEARCH RECURSIVE

AIM:

To write a C++ program to perform a recursive binary search.

ALGORITHM:

1. Start the program.


2. Declare the mid, n, x and array in integer type.
3. Declare void get( ), int search( ) and void complex( ) functions in public mode.
4. Get the values in void get( ) functions.
5. Search the element in the int search(int[ ], int, int) function.
6. Calculate the space and time complexity using void complex( ) function.
7. In the main function call all the three functions and display the position of the
search element.
8. Stop the program.

CODING:

CSBS DEPT / ALGORITHMS LAB (P41)


Page 7
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

# include <iostream.h>
# include <conio.h>
# include<math.h>
class binary
{
public:
int x,a[50],mid,n;
void get();
int search(int[],int,int,int);
void complex();
};
void binary::get()
{
cout<<"\n BINARY SEARCH";
cout<<"\n enter the size of array:";
cin>>n;
cout<<"\n enter the elements:";
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<"\n enter the elements to searched:";
cin>>x;
}

int binary::search(int a[],int i,int l,int xi)


{
if(l==i)
{
if(xi==a[i])
return i;

CSBS DEPT / ALGORITHMS LAB (P41)


Page 8
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

else
return 0;
}
else
{
mid=(i+l)/2;
if(xi==a[mid])
return mid;
else
if(xi<a[mid])
return search(a,i,mid-1,xi);
else
return search(a,mid+1,l,xi);
}
}
void binary::complex()
{
cout<<"\n\nTime Complexity is O("<<log(n)<<")"<<"\n";
cout<<"\nSpace Complexity is O("<<n<<")";
}
int main()
{
int s;
clrscr();
binary bi;
bi.get();
s=bi.search(bi.a,1,bi.n,bi.x);
if(s==0)
cout<<"Element not found";
else

CSBS DEPT / ALGORITHMS LAB (P41)


Page 9
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

cout<<"Element is found in "<<s<<"position";


bi.complex();
getch();
return 0;
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 10
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for recursive binary search has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 11
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:2

MERGE SORT

AIM:

To write a C++ program to perform merge sort.

ALGORITHM:

1. Start the program.


2. Declare low, high, mid, array, n, I and b array in integer type.
3. Declare void get( ), void mergesort( ), void merge( ), void display( ) and void
complex( ) in public mode.
4. Get the values in void get( ) function.
5. Sort the array elements using the void mergesort( ) function.
6. Then merge the sorted elements using the void merge( ) function.
7. Display the elements using void display( ) function.
8. Calculate the time and space complexity using the void complex( ) function.
9. In the main( ) function call all the functions and perform merge sort.
10. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 12
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:
#include<iostream.h>
#include<conio.h>
#include<math.h>
class merg
{
public:
int low,high,mid,i,a[20],n,b[20];
void getdata();
void mergesort(int,int);
void merge(int,int,int);
void display();
void complex(int);
};
void merg::getdata()
{
int i;
cout<<"\nEnter the number of array elements:";
cin>>n;
cout<<"\nEnter the array elements:";
for(i=1;i<=n;i++)
cin>>a[i];
}
void merg::mergesort(int low,int high)
{ int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(low,mid);
mergesort(mid+1,high);

CSBS DEPT / ALGORITHMS LAB (P41)


Page 13
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

merge(low,mid,high);
}
}
void merg::merge(int low,int mid,int high)
{
int h,k,i,j;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h=h+1;
}
else
{
b[i]=a[j];
j=j+1;
}
i=i+1;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i=i+1;
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 14
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i=i+1;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
void merg::display()
{
int i;
cout<<"\nThe sorted array is:";
for(i=1;i<=n;i++)
{
cout<<a[i]<<endl;
}
}
void merg::complex(int n)
{
cout<<"\n\nTime Complexity is O("<<n*log(n)<<")"<<endl;
cout<<"\nSpace Complexity is O("<<n<<")"<<endl;
}
void main()
{
int l,h;
clrscr();

CSBS DEPT / ALGORITHMS LAB (P41)


Page 15
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

merg m;
m.getdata();
l=1;
h=m.n;
m.mergesort(l,h);
m.display();
m.complex(h);
getch();
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 16
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for merge sort has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 17
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:3

QUICK SORT

AIM:

To implement a quick sort program usin C++.

ALGORITHM:

1. Start the program.


2. Declare a[ ], n, I, j, p, q, m, v in integer data type o public specifier.
3. Declare the getdata( ), for getting array elements.
4. Declare quick sort( ) now perform the sorting process.
5. Declare partition ( ) to divide the elements using a pivot element.
6. Declare interchange( ) to swap the values of i, j and p.
7. Declare display( ) to view the sorted data.
8. Declare the complex( ) to view the time and space complexity.
9. In the main function invoke all the functions above using the object.
10. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 18
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>

#include<conio.h>

#include<math.h>

class quick

public:

int j,i,n,a[20];

void get()

cout<<"\n\t...<<<QUICK SORT>>>...";

cout<<"\n\tEnter No of Elements:";

cin>>n;

cout<<"\n\tEnter the Elements:";

for(i=1;i<=n;i++)

cin>>a[i];

a[n+1]=32000;

void quick_sort(int p,int q)

if(p<q)

j=part(a,p,q+1);

quick_sort(p,j-1);

quick_sort(j+1,q);
CSBS DEPT / ALGORITHMS LAB (P41)
Page 19
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

int part(int a[],int low,int high)

int v=a[low],i=low,j=high;

do

do

{ i=i+1;

} while(a[i]<v);

do

{ j=j-1;

} while(a[j]>v);

if(i<j)

interchange(a,i,j);

}while(i<j);

a[low]=a[j];

a[j]=v;

return j;

int interchange(int a[],int i,int j)

int m;

m=a[i];
CSBS DEPT / ALGORITHMS LAB (P41)
Page 20
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

a[i]=a[j];

a[j]=m;

void disp()

cout<<"The Sorted Array:";

for(i=1;i<=n;i++)

cout<<"\n"<<a[i];

void complex(int n)

cout<<"\n\tTime Complexity:O("<<n*n<<")";

cout<<"\n\t SpaceComplexity:O("<<n<<")";

};

void main()

clrscr();

quick q;

q.get();

q.quick_sort(1,q.n);

q.disp();

q.complex(q.n);

getch();

}
CSBS DEPT / ALGORITHMS LAB (P41)
Page 21
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for quick sort has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 22
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:4
GREEDY METHOD
PRIM’S ALGORITHM

AIM:

To write a C++ program to implement prim’s algorithm using greedy method.

ALGORITHM:

1. Create a class prim

2. Declare cost [50][50],min,k,l as long integer and n, mincost e, jmin as integer.

3. Define a method get() to get the number of vertices.

4. Repeat for i=1to n and for j=i to n.

5. Check if (i==j) then assign cost[i][j]=32000.

6. Else get the cost of all the edges.

7. Define another method compute () declare i , j as integer.

8. Assign min=cost[1][1].

9. Repeat for i=1 to n do

10. Repeat for j=1 to n do

11. Check if (min>cost[i][j]) then assign min=cost[i][j], k=i,l=j.

12. Define another method prim () , declare t[10][2], nea[10] as integer .

13.Assign mincost=cost[k][l] , t[1][1] =k, t[1][2]=l.

14. Repeat for i=1 to n , check if(c[i][l]<c[i][k]) then nea[i]=l.

15. Else nea[i] =k.

16. Repeat for e=2 to (n-1) do assign jmin= 32000.

17. Repeat for i =1 to n ,check if((nea[i]!=0) and (jmin>c[i][nea[i]])) then jmin=c[i]


[nea[i]] and j=i.

18Assign t[e][1] =j,t[e][2]=nea[j] , mincost =mincost +jmin ,nea[j]=0.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 23
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

19.Repeat for k=1 to n , check if( nea[k]!=0 and (c[k][nea[k]]>c[k][j])) then nea[k] =j.

20. Define a method display() to display the minimum cost .

21. In the main() invoke all the methods by creating object for the class prim.

22. Stop the program execution.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 24
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>

#include<conio.h>

class prims

int i,j,k,l,near1[50];

int cost[50][50],t[50][50];

int min,mincost;

public:

void prim(int n);

};

//GETS THE INPUT

void prims::prim(int n)

cout<<"\nIf there is no edge then enter 9999\n";

for(i=1;i<=n;i++)

for(j=i;j<=n;j++)

if(i!=j)

cout<<"\nThe cost between "<<i<<" and "<<j<<" : ";

cin>>cost[i][j];

cost[j][i]=cost[i][j];

if(cost[i][j]<min)
CSBS DEPT / ALGORITHMS LAB (P41)
Page 25
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

min=cost[i][j];

k=i;

l=j;

//DISPLAYS THE ADJACENCY MATRIX OF THE GRAPH

cout<<"\nThe adjacency matrix is:\n ";

for(i=1;i<=n;i++)

cout<<"\n";

for(j=1;j<=n;j++)

cout<<"\t"<<cost[i][j];

//FINDS THE MINIMUM SPANNING TREE AND ITS MINIMUM COST

mincost=cost[k][l];

t[1][1]=k;

t[1][2]=l;

for(i=1;i<=n;i++)

if(cost[i][l]<cost[i][k])
CSBS DEPT / ALGORITHMS LAB (P41)
Page 26
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

near1[i]=l;

else

near1[i]=k;

near1[k]=0;

near1[l]=0;

for(i=2;i<=n-1;i++)

min=9999;

for(int a=1;a<=n;a++)

if((near1[a]!=0)&&(min>cost[a][near1[a]]))

min=cost[a][near1[a]];

j=a;

t[i][1]=j;

t[i][2]=near1[j];

mincost=mincost+min;

near1[j]=0;
CSBS DEPT / ALGORITHMS LAB (P41)
Page 27
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

for(k=1;k<=n;k++)

if((near1[k]!=0)&&(cost[k][near1[k]]>cost[k][j]))

near1[k]=j;

}}

//PRINTS THE EDGES IN MINIMUM SPANNING TREE

cout<<"\n\nMinimum Cost is : "<<mincost;

cout<<"\n\nThe Minimum Spanning Tree is : \n\n";

for(i=1;i<=n-1;i++)

cout<<t[i][1]<<" -> "<<t[i][2]<<"\n";

}}

void main()

int n;

prims pr;

clrscr();

cout<<"\nPRIMS ALGORITHM\n";

cout<<"\nEnter the number of vertices:";

cin>>n;

pr.prim(n);

getch();

}
CSBS DEPT / ALGORITHMS LAB (P41)
Page 28
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for prim’s algorithm has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 29
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:5

KRUSKAL’S ALGORITHM

AIM:

To write a C++ program to implement kruskal’s algorithm using greedy method.

ALGORITHM:

1. Create a class kruskal.

2. Declare parent[100] , i, j ,a[10][10] ,x[20],j[20],z[20],t[20][20], te,mincost , r, n,x1,x2


as integer.

3. Define a method find1 () with argument ( i)

4. Repeat for while (parent [i]>0) do

5. Assign i=parent[i] ,return i.

6. Define a method union1 () with two arguments (x1, x2)

7. Assign parent[x1]= x2.

8. Define a method getdata() to get the number of nodes and to find whether the path
exists.

9. Check if( i<j) and (a[i][j]!=0) then x[k] = i,y[k]=j,z[k]=a[i][j].

10. Check if(i<j) then

11. Again check if(z[i]>z[j]) then swap x[],y[],z[] using temporary variable.

12. Assign n1=k-1, repeat for i=1 to n do parent[i] = -1. Declare r=1, mincost =0.

13. Repeat while (i<n-1) and (r!=n) do.

14. Declare u=x[r],v=y[r] , j=find [u] and k=find[v].

15. Check if(j!=k) then increment i, t[i][1]=u ,t[i][2] =v , mincost =mincost +z[r] and call
union1(j,k) and increment r.

16. Define a method putdata() inorder to display the minimum cost of the tree.

17. Invoke all the methods by creating object for the class kruskal.

18. Stop the program execution.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 30
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>

#include<conio.h>

class kruskals

int parent[100],cost[20][20],x[20],y[20],t[10][10],z[20];

int mincost,u,v,i,r,temp,n1,j,k;

public:

void kruskal(int);

int find1(int);

void union1(int,int);

};

void main()

int n;

kruskals kr;

clrscr();

cout<<"\nKRUSKALS ALGORITHM\n";

cout<<"\nEnter the number of nodes : ";

cin>>n;

kr.kruskal(n);

getch();

void kruskals::kruskal(int n)

{
CSBS DEPT / ALGORITHMS LAB (P41)
Page 31
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

k=1;

cout<<"\nIf no edge exists enter 9999\n";

for(i=1;i<n;i++)

for(j=i+1;j<=n;j++)

cout<<"\nThe cost between "<<i<<" and "<<j<<" : ";

cin>>cost[i][j];

if((i<j)&&(cost[i][j]!=0))

x[k]=i;

y[k]=j;

z[k]=cost[i][j];

k++;

for(i=1;i<k;i++)

for(j=1;j<k;j++)

if((i<j)&&(z[i]>z[j]))

temp=z[i];z[i]=z[j];z[j]=temp;
CSBS DEPT / ALGORITHMS LAB (P41)
Page 32
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

temp=x[i];x[i]=x[j];x[j]=temp;

temp=y[i];y[i]=y[j];y[j]=temp;

n1=k-1;

for(i=1;i<=n;i++)

parent[i]=-1;

r=1;

mincost=0;

i=0;

while((i<n-1)&&(r!=n1))

u=x[r];

v=y[r];

j=find1(u);

k=find1(v);

if(j!=k)

i=i+1;

t[i][1]=u;

t[i][2]=v;

mincost=mincost+cost[u][v];
CSBS DEPT / ALGORITHMS LAB (P41)
Page 33
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

union1(j,k);

r++;

cout<<"\nMINIMUM SPANNING TREE\n\n";

for(i=1;i<n;i++)

cout<<"\t"<<t[i][1]<<"->"<<t[i][2];

cout<<"\n\n Minimum Cost is = "<<mincost;

getch();

int kruskals::find1(int i)

while(parent[i]>=0)

i=parent[i];

return i;

void kruskals::union1(int x1,int x2)

parent[x1]=x2;

CSBS DEPT / ALGORITHMS LAB (P41)


Page 34
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for kruskal’s algorithm has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 35
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:6
SINGLE SOURCE SHORTEST PATH

AIM:

To implement a c++ program for single source shortest path.

ALGORITHM:

1. Start the program.


2. Declare a class dijisktras and class member cost[10:10],n,u,w,dist[10],I,s[10],v.
3. Get the values of cost adjacency matrix and no.of vertices n.
4. For(i=1 to n) assign the values for s[i]=0 and dist[i]=cost[v,i].
5. Assign s[v]=1 and dist[v]=0.
6. From num=2 to n-1 do choose u from those vertices where s[i]=0.
7. Assign s[u]=1.
8. For each w adjacent to u with s[w]=0 do.
9. If dist[w]>dist[u]+cost[u,w] then assign dist[w]=dist[u]+cost[u,w].
10. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 36
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>
#include<conio.h>
class path
{
private:
int i,j,min,n,cost[10][10],dist[10];
int u,v,w,num,s[10];
public:
void getdata();
void spath();
void display();
void distance();
};
void path::getdata()
{
cout<<"\n\t\t**** SINGLE SOURCE SHORTEST PATH**** ";
cout<<"\n\n\nEnter the number of nodes : ";
cin>>n;
cout<<"\nIf there is no edge then enter 9999\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
{
cost[i][j]=9999;
}
else
{
cout<<"\nEnter the cost between "<<i<<" and "<<j<<" : ";
cin>>cost[i][j];
}
}
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 37
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

}
void path::display()
{
cout<<"The Adjacency Matrix \n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cout<<cost[i][j]<<"\t";
}
cout<<"\n";
}
}

void path::spath()
{
cout<<"\nEnter the source vertex : ";
cin>>v;

for(i=1;i<=n;i++)
{
s[i]=0;
dist[i]=cost[v][i];
}
s[v]=1;
dist[v]=0;
for(num=2;num<=n-1;num++)
{
min=9999;
for(j=1;j<=n;j++)
{
if((s[j]==0)&&(min>dist[j]))
{
min=dist[j];
u=j;
}
CSBS DEPT / ALGORITHMS LAB (P41)
Page 38
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

}
s[u]=1;
for(w=1;w<=n;w++)
{
if((s[w]==0)&&(dist[w]>dist[u]+cost[u][w]))
{
dist[w]=dist[u]+cost[u][w];
}
}
cout<<"\n";
}
}

void path::distance()
{
for(w=1;w<=n;w++)
{
cout<<"Distance between " << v << " to " << w << " is " <<dist[w];
cout<< "\n";
}
}
void main()
{
clrscr();
path p;
p.getdata();
p.display();
p.spath();
p.distance();
getch();

CSBS DEPT / ALGORITHMS LAB (P41)


Page 39
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for single source shortest path was executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 40
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:7

DYNAMIC PROGRAMMING
ALL PAIR SHORTEST PATH

AIM:

To implement a c++ program for all pair shortest path.

ALGORITHM:

1. Start the program.


2. Declare a class path.
3. Declare a[20][20],cost[20][20],I,j,n,t as global.
4. Define a function get() to get the no.of vertices and using for loop to get the cost,cost[i][j].
5. Define a function all pair (a[20][20],n) using three for loop and check if a[i][k]+a[k][j]
+a[i][j] and update a[i][j].
6. Define a function display() to display a[i][j] in matrix format using two for loop.
7. In main function, declare an object class path.
8. Invoke all functions using object.
9. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 41
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>
#include<conio.h>
int a[20][20],cost[20][20],i,j,n,k;
class path
{
public:
void get(); // TO GET THE COST OF EDGES
void allpair(int a[20][20],int); // TO FIND THE SHORTEST PATH
void display(); // TO DISPLAY THE OUTPUT MATRIX
};

// GETS THE COST OF EACH EDGE

void path::get()
{
cout<<"\n\t\tALL PAIRS SHORTEST PATH ALGORITHM";
cout<<"\n\nEnter the total no of vertices:";
cin>>n;
cout<<"\nEnter the cost:";
cout<<"\n\nIf there is no edge enter 9999\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
{
cost[i][j]=0;
a[i][j]=0;
}
else
{
cout<<"\nEnter the cost between "<<i<<" and "<<j<<" : ";

CSBS DEPT / ALGORITHMS LAB (P41)


Page 42
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

cin>>cost[i][j];
a[i][j]=cost[i][j];
}
}
}
}
void path::allpair(int a[20][20], int n)
{
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if((a[i][k]+a[k][j])<a[i][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
}
void path::display()
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cout<<a[i][j];
cout<<"\t";
}
cout<<"\n\n";
}
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 43
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

void main()
{
path p;
clrscr();
p.get();
cout<<"\n\nADJACENCY MATRIX\n\n";
p.display();
p.allpair(a,n);
cout<<"\nALL PAIRS SHORTEST PATH\n\n";
p.display();
getch();
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 44
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for all pair shortest path has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 45
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:8

OPTIMAL BINARY SEARCH TREE

AIM:

To write a C++ program to implement OBST using dynamic programming.

ALGORITHM:

1. Start

2. Declare the class binser with data member p[10],q[10], w[10][10], c[10][10], r[10]
[10],n,i,j,k as integer variable.

3. Declare the member function get()-to get the value of no of nodes , probability of
internal and external nodes.

4. Declare the member function compute(),to initialize w[i,j]=q[i]; R[i,i]=0; C[i,i]=0.0;

//obst with one node

w[i,i+1]=q[i]+q[i+1]+p[i+1]; R[i][i+1]=i+1;C[i][i+1]=q[i]+q[i+1]+p[i+1]

5. For loop is used for m variable m=2 to <=n do

i=0 to n-m do

j=i+m

w[i,j]=w[i][j-1]+p[j]+q[j];

k=find(c,r,i,j)

c[i][j]=c[i][k-1]+c[k][j]+w[i][j]

r[i][j]=k

6. Check l=1 to <=n using for loop and print” OPTIMAL BINARY SEARCH TREE”

again i=0 to n-1 do j=i+1

7. Declare sub function find(int a[10][10],int b[10][10],int c,int d)

8.Declare with data member e,f,min=32000 and l as integer

e=b[c][d-1]

CSBS DEPT / ALGORITHMS LAB (P41)


Page 46
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

f=b[c+1][d]

9.Check h=e to f do

if((a[c][h-1]+a[h][d])<min) than

min=a[c][h-1] + a[h][d]; l=h return l

10. In main declare b as the object to access the function of the class using dot operator.

11. End the program

CSBS DEPT / ALGORITHMS LAB (P41)


Page 47
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:
# include<iostream.h>
# include<conio.h>
class binser
{
public:
int p[10],q[10],w[10][10],c[10][10],r[10][10],n,i,j,k;
void get()
{
cout<<"\n enter the no. of nodes:";
cin>>n;
cout<<"\n enter the probability of internal node";
for(i=1;i<=n;i++)
cin>>p[i];
cout<<"\n enter the probability of external node";
for(i=0;i<=n;i++)
cin>>q[i];
}
void compute()
{
int m;
for(i=0;i<n;i++)
{
w[i][i]=q[i];
r[i][i]=0;
c[i][i]=0;
w[i][i+1]=q[i]+q[i+1]+p[i+1];
r[i][i+1]=i+1;
c[i][i+1]=q[i]+q[i+1]+p[i+1];
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 48
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

w[n][n]=q[n];
r[n][n]=0;
c[n][n]=0;
for(m=2;m<=n;m++)
{
for(i=0;i<=n-m;i++)
{
j=i+m;
w[i][j]=w[i][j-1]+p[j]+q[j];
k=find(c,r,i,j);
c[i][j]=c[i][k-1]+c[k][j]+w[i][j];
r[i][j]=k;
}}
for(int l=1;l<=n;l++)
{
cout<<"\noptimal Binary search Tree with"<<l<<"node";
for(i=0;i<=n-l;i++)
{
j=i+l;
cout<<"\n w["<<i<<"]["<<j<<"]"<<w[i][j]<<"\tc[";
cout<<i<<"]["<<j<<"]"<<c[i][j]<<"\tr["<<i<<"]["<<j<<"]"<<r[i][j];
cout<<"\n";
}
cout<<"\n------------------------------";
}
}
int find(int a[10][10],int b[10][10],int c,int d)
{
int e,f,min=32000,l;
e=b[c][d-1] ;

CSBS DEPT / ALGORITHMS LAB (P41)


Page 49
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

f=b[c+1][d] ;
for(int h=e;h<=f;h++)
{
if((a[c][h-1]+a[h][d]) <min)
{
min=a[c][h-1]+a[h][d];
l=h;
}
}
return l;
}
};
void main()
{
clrscr();
binser b;
b.get();
b.compute();
getch();
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 50
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for optimal binary search tree has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 51
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:9

BACKTRACKING
NQUEEN PROBLEM

AIM:

To write a C++ program to implement n-queen problem using backtracking.

ALGORITHM:

1. Start

2. Create a class nqueen and declare the data members , member functions, x[20],n,k as
integer variables.

3. Get function is used to get the input data .

4. Function queen is used and k,n are the parameters passed as integer data type.
5. For loop is used to compute if(place(k,i)==1)then
6. Assign n[k]=i;
7. If (k==n)then open a for loop to print the x[i] value else queen (k+1,n).
8. Close all if and for loop,get function is also closed.
9. Sub function place is defined as a parameterized function.
10. For loop is used using j variable j=1 to k-1
11. If ((x[j]=i or ((abs x[j]-i) = abs (j-k)) ,Return false (0),else return (1),sub d=function
terminates.
12. In Main function ,a reference variable nq is created for nqueen.
13. The object is used to access the get function and queen functions.
14. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 52
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>
#include<conio.h>
#include<math.h>
class queen
{
public:
int n,k,t,x[50];
void get();
void nqueens(int,int);
int place(int,int);
};
void queen::get()
{
cout<<"\n\t\tNQUEENS PROBLEM.";
cout<<"\nEnter the no of queens :";
cin>>n;
nqueens(1,n);
}
void queen::nqueens(int k,int n)
{
for(int i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
cout<<"\n\nThe solution is\n";

CSBS DEPT / ALGORITHMS LAB (P41)


Page 53
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

for(int j=1;j<=n;j++)
{
cout<<"\n";
cout<<"\n Queen "<<j<<"\t"<<x[j];
}
}
else
{
nqueens(k+1,n);
}
}

int queen::place(int k,int i)

for(int j=1;j<k;j++)

if((x[j]==i)||(abs(x[j]-i)==abs(j-k)))

return 0;

return 1;

void main()

int n;
CSBS DEPT / ALGORITHMS LAB (P41)
Page 54
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

clrscr();

queen q;

q.get();

getch();

CSBS DEPT / ALGORITHMS LAB (P41)


Page 55
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for N queen problem has been executed successfully.
CSBS DEPT / ALGORITHMS LAB (P41)
Page 56
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:10

SUM OF SUBSETS

AIM:

To write a C++ program to implement sum of subsets using backtracking.

ALGORITHM:

1. Start.
2. Create a class subset and declare the data members and define the member function.
3. Input data is obtained by get function,where count,r is assigned to 0.
4. The input for weight is obtained by for loop,then assign the solution vector to 0.
5. Assign S to 0,k=1 and then terminate the function.
6. Sumofsubset function is used to do operation and it is defined as parameterized function
with variable s,k and r.
7. Assign vector solution to 1,if (s+w[k]=m) where m is the max capacity.
8. Count is incremented and call display function,
a. a)count is used to display the solution ,for loop is used to print the solution vector.
b. b)another for loop is used by assigning solution vector to 0.
9. return to sumofsubset function else part if (s+w[k]+w[k+1]<=m) then sumofsubset
(s+w[k],k+1,r-w[k]).
10. if ((s+r-w[k]>=m)&&(s+w[k+1]<=m)) assign solution vector to 0 and call
Sumofsubset(s,k+1,r-w[k]).

11. Terminate the sumofsubset function and class.


12. In main function create the reference variable for class subset as si.
13. Using si object access the getdata and sumofsubset from the class.
14. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 57
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>

#include<conio.h>

int w[20],x[20],m;

float r;

class subset

public:

void getdata();

void print(int);

void sumofsub(float,int,float);

};

void subset::getdata()

int i,n;

cout<<"\nEnter the value of N:";

cin>>n;

cout<<"\nEnter the capacity:";

cin>>m;

r=0;

for(i=1;i<=n;i++)

cout<<"\nWeight "<<i<<":";

cin>>w[i];

r=r+w[i];
CSBS DEPT / ALGORITHMS LAB (P41)
Page 58
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

// s - loaded

// r - remaining

// w[k] - current load

// k - load number

// m - capacity

void subset::sumofsub(float s,int k,float r)

x[k]=1;

if(s+w[k]==m)

print(k);

else if (s+w[k]+w[k+1] <= m)

sumofsub(s+w[k],k+1,r-w[k]);

if((s+r-w[k] >= m) && (s+w[k+1] <= m))

x[k]=0;

sumofsub(s,k+1,r-w[k]);

}
CSBS DEPT / ALGORITHMS LAB (P41)
Page 59
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

void subset::print(int k)

int j;

for(j=1;j<=k;j++)

cout<<x[j]<<"\t";

cout<<"\n\n";

void main()

clrscr();

subset s1;

cout<<"\n\n SUM OF SUBSET:\n\n";

s1.getdata();

s1.sumofsub(0,1,r);

getch();

CSBS DEPT / ALGORITHMS LAB (P41)


Page 60
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for sum of subset has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 61
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:11

GRAPH COLORING

AIM:

To write a C++ program to implement graph coloring using backtracking.

ALGORITHM:

1. Start.
2. Declare the class graph,with data member k,m,n,x[20],i,j,g[20][20]as integer variable.
3. Declare the function getdata() to get the value of the limit and max color,
a. a)check for(i=1;i<=n;i++) do x[j]=0.
b. b) check for (j=1;j<=n;j++) do get the value of g[i][j].
4. Declare the function mcolor() with data member t as int, next value (t) if (x[k]=0)then
return else if (t==n)
5. Display the value for (i=1;i<=n;i++),print “x[i]”else mcolor(t+1).
6. Declare sub function next value() with parameter k as int , x[k]=(x[k]+1)%(m+1).
7. Print “color cannot be done” for (j=1;j<=n;j++)
a. if ((g[k][j]!=0)&&(x[k]==x[j])) the break.
8. In main function,reference variable gc is created to access the function as object using.
9. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 62
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:

#include<iostream.h>
#include<conio.h>
#include<process.h>
int k,m;
class graph
{
int n,x[20],i,j,g[20][20];
public:
void get();
void mcolor(int);
void nextvalue(int);
};

void graph::get()
{
cout<<"\nEnter the no. of vertices of graph:";
cin>>n;
cout<<"\Enter the adjacency edge:\n";
cout<<"\Enter 0 if there is no edge\n";
for(i=1;i<=n-1;i++)
{
for(j=i+1;j<=n;j++)
{
cout<<i<<" to "<<j<<" = ";
cin>>g[i][j];
g[j][i]=g[i][j];
}
}
cout<<"\nEnter the no. of colors:";
cin>>m;
}
CSBS DEPT / ALGORITHMS LAB (P41)
Page 63
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

void graph::mcolor(int k)
{
do
{
nextvalue(k);
if(x[k]==0) // New color not found
{
return;
}

if(k==n) // Color assigned to all node

{
cout<<"Solutions are: \n";
for(i=1;i<=n;i++)
{
cout<<"\t"<<x[i]<<"\t";
}
cout<<"\n";
}
else
{
mcolor(k+1);
}
} while(1);
}
// Find next color
void graph::nextvalue(int k)
{
do
{
x[k]=(x[k]+1)%(m+1); // Assign Next color

CSBS DEPT / ALGORITHMS LAB (P41)


Page 64
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

if(x[k]==0)
{
return;
}
// Compare color with adjacent node
for(j=1;j<=n;j++)
{
if((g[k][j] > 0) && (x[k]==x[j]))
{
break;
}
}

if(j==n+1)
{
return;
}
}while(1);
}
void main()
{
clrscr();
graph gc;
gc.get();
gc.mcolor(1);
getch();
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 65
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

Thus the c++ program for graph coloring has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 66
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Ex.No:12

HAMILTONIAN CYCLE

AIM:

To write a C++ program to implement Hamiltonian cycle using backtracking.

ALGORITHM:

1. Start .
2. Declare the class hamal with data member n,k,x[20],g[20][20] and member function .
3. Declare the function get() with data member f as char and get the value of no.of nodes
and the path of n nodes.
a)If(i==j)then g[i][j]=0 else
4. Get the value of the edge if(f==t),g[i][j]=1,g[j][i]=1
a)Else g[j][i]=0,g[i][j]=0 for int (l=2;l<=n;l++),then x[1]=0;
5. Declare the sub function hamil(int k)with data member i as int,
a)If (x[k]=0) then return
b)If (k==n)then write(x[1:n]);
c)Else hamil (k+1).
6. Declare the sub function next (int k) with data members j,q,p,a,b as int
a) X[k]=(x[k]+1)%(n+1),if (x[k]==0) return 1
b) P=x[k-1],q=x[k],if (g[p][q]!=0)then For(j=1;j<=k-1;j++)
c) If (x[j]==x[k] )then break
d) If (j=k)then if (k<n)or (k=n)and G(x[n],x[1]≠0) then return until (false)
7. In main function, create the reference variable h as object to access the function get and
hamil.
8. Stop the program.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 67
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

CODING:
#include<iostream.h>
#include<conio.h>
class hamal
{
public:
int n,k,x[20],g[20][20];
void get()
{
char f;
int i,j;
cout<<"\nEnter the number nodes:";
cin>>n;
cout<<"\nEnter the path:";
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
if(i==j)
g[i][j]=0;
else
{
cout<<"\n there is a edge b/w"<<i<<"and"<<j;
cin>>f;
if (f=='t')
{
g[i][j]=1;
g[j][i]=1;
}
else
{
g[i][j]=0;

CSBS DEPT / ALGORITHMS LAB (P41)


Page 68
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

g[j][i]=0;
}
}
}
}
x[1]=1;
for(int l=2;l<=n;l++)
x[l]=0;
}
int hamil(int k)
{
int i;
while(1)
{
next(k);
if(x[k]==0)
{
return(0);
}
if(k==n)
{
for(i=1;i<=n;i++)
{
cout<<x[i]<<"\t";
}cout<<"\n"<<"\n";
}
else
hamil(k+1);
}
}

int next(int k)
{
int j,p,q,a,b;
CSBS DEPT / ALGORITHMS LAB (P41)
Page 69
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

do
{
x[k]=((x[k]+1)%(n+1));
if(x[k]==0)
return(1);
p=x[k-1];
q=x[k];
if(g[p][q]!=0)
{
for(j=1;j<=k-1;j++)
{
if(x[j]==x[k])
break;
}
if(j==k)
{
a=x[n];
b=x[1];
if((k<n)||((k==n)&&(g[a][b]!=0)))
return(1);
}
}
}while(1);
}
};
void main()
{
clrscr();
hamal h;
h.get();
h.hamil(2);
getch();
}

CSBS DEPT / ALGORITHMS LAB (P41)


Page 70
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:

RESULT:

CSBS DEPT / ALGORITHMS LAB (P41)


Page 71
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Thus the c++ program for hamiltonian cycle has been executed successfully.

CSBS DEPT / ALGORITHMS LAB (P41)


Page 72

You might also like