0% found this document useful (0 votes)
49 views55 pages

It Lab 1

The document describes experiments implementing different sorting algorithms in C++. Experiment 1 implements quicksort, with steps including declaring variables, reading array elements, selecting a pivot element, and sorting elements around the pivot. Experiment 2 implements merge sort, with steps like dividing the array, merging sorted halves. Experiment 3 implements Prim's algorithm for minimum spanning trees, including initializing a distance matrix and selecting edges with minimum distance. Experiment 4 similarly implements Kruskal's algorithm for minimum spanning trees.

Uploaded by

Mani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
49 views55 pages

It Lab 1

The document describes experiments implementing different sorting algorithms in C++. Experiment 1 implements quicksort, with steps including declaring variables, reading array elements, selecting a pivot element, and sorting elements around the pivot. Experiment 2 implements merge sort, with steps like dividing the array, merging sorted halves. Experiment 3 implements Prim's algorithm for minimum spanning trees, including initializing a distance matrix and selecting edges with minimum distance. Experiment 4 similarly implements Kruskal's algorithm for minimum spanning trees.

Uploaded by

Mani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

Expt.

No: 1 IMPLEMENTATION OF QUICK SORT Date:

AIM
To write a C++ program to perform Quick sort using Divide and conquer technique.

ALGORITHM
Step 1: Start the program.
Step 2: Declare the necessary variables and an array that are going to use in the program.
Step 3: Read the number of value to be stored in the array.
Step 4: Read the elements of the array one by one.
Step 5: Select the first element and the last element called pivot from the array and compare
with the other elements from the both sides of the array.
Step 6: The elements which are lesser than the pivot element is placed before the pivot element
and greater placed after the pivot element.
Step 7: Then the array is divided into two. And then repeat number 5 and 6 on both halves of
the array until the sorting is done completely.
Step 8: Print the sorted array.
Step 9: Stop the program.

1
PROGRAM
#include<iostream.h>
#include<conio.h>
int a[10],i,j,n,temp,pivot;
class quicksort
{
public:
void get();
void sort(int,int);
void interchange(int[],int,int);
int partition(int[],int,int);
void put();
void complex();
};
void main()
{
quicksort r;
clrscr();
r.get();
r.sort(0,n-1);
r.put();
r.complex();
getch();
}
void quicksort::get()
{
cout<<"\nEnter the number of elements:";
cin>>n;
cout<<"Enter the numbers:\n"; for(i=0;i<n;i++)
{
cin>>a[i];
}
}
void quicksort::sort(int left,int right)

2
{
if(left<right)
{
j=partition(a,left,right);
sort(left,j-1);
sort(j+1,right);
}
}
int quicksort::partition(int a[],int left,int right)
{
if(left<right)
{
pivot=a[left];
i=left;
j=right+1; do
{
do
{
i++;
}while(a[i]<pivot);
do
{
j--; }while(a[j]>pivot);
if(i<j)
{
interchange(a,i,j);
}
}while(i<j);
interchange(a,left,j);
}
return j;
}
void quicksort::interchange(int a[],int i,int j)
{

3
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void quicksort::put()
{
cout<<"Sorted elements are:\n"; for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
}

4
OUTPUT

RESULT
Thus, the program for quick sort was executed successfully.

5
Expt. No: 2 IMPLEMENTATION OF MERGE SORT Date:

AIM
To write a C program to implement merge sort using divide and conquer.

ALGORITHM
Step 1: Start the program.
Step 2: Declare the variables and two arrays of elements.
Step 3: Read the value of number of elements to be stored in the two arrays.
Step 4: Read the values of the elements of two arrays.
Step 5: Compare the first element with the last element, if the first is lesser than the last element
compute the middle by mid=(low +high)/2 value sort and split the array as first, middle,
middle+1, and the last.
Step 6: Compare two arrays, if the 0th element of the first array (a[i]) is smaller than the 0th
element of the second (b[i]) array then put the 0th element of the first array in the third array
to be merged.
Step 7: Then compare the 1st element of a[i] with the 0th element of b[i] and repeat the steps.
Step 8: Print the sorted third array.
Step 9: Stop the program

6
PROGRAM
#include<stdio.h>
#include<conio.h>
void merge_split(int a[], int first, int last);
int merge(int a[],int f1, int l1, int f2, int l2);
int a[25], b[25];
void main()
{
int i,n;
clrscr();
printf("\n\t\t MERGE SORT\t\t\n");
printf("\n Enter the limit:");
scanf("%d", &n);
printf("\n Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
merge_split(a,0,n-1);
printf("\n\n The sorted array is:");
for(i=0;i<n;i++)
printf("\n%d\n",a[i]);
getch();
}
void merge_split(int a[], int first, int last)
{
int mid, size;
size=last-first+1;
if(size<=1)
{return;
}
mid=first+(size/2)-1;
merge_split(a,first,mid);
merge_split(a,mid+1,last);

7
merge(a,first,mid,mid+1,last);
}
int merge(int a[], int f1, int l1, int f2, int l2)
{
int i,j,k=0;
i=f1;
j=f2;
while(i<=l1&&j<=l2)
{
if(a[i]<a[j])
{
b[k]=a[i];
i++;
k++;
}
else
{
b[k]=a[j];
j++;
k++;
}
}
while(i<=l1)
b[k++]=a[i++];
while(j<=l2)
b[k++]=a[j++];
i=f1;
j=0;
while(i<=l2&&j<k)
a[i++]=b[j++];
return a[i];
}

8
OUTPUT

RESULT
Thus, the program for merge sort was executed successfully.

9
Expt. No: 3 IMPLEMENTATION OF PRIMS ALGORITHM Date:

AIM
To write a C++ program to implement Minimum spanning tree using Prims algorithm

ALGORITHM

Step 1: Start the program


Step 2: Declare the necessary variable and array
Step 3: Read the number of edges from the user and assign to “n”
Step 4: Set the visited[i]=0 for all vertices that initially all the nodes as unvisited node
Step 5: Choose any vertex,so that the selected vertex is the root of minimum spanning tree.
Step 6: Set the initial distance as infinity, for each and every vertex enter the corresponding
edge and its distance. If no direct connection between edges enterthe weight as infinity that is
9999
Step 7: Display the distance matrix for all vertex.
Step 8: To find the shortest path set the initial root vertex as visited.
(a) Find a lightest edge from visited to other vertex.
(b) If vertex with less distance is found add this edge to minimum spanning tree v and
repeat step Step 8 (a) until all the vertex are visited.
Step 9: If all the nodes are visited then display the shortest path between the nodes visited as
minimum spanning tree.
Step 10: Stop the program

10
PROGRAM
#include<iostream.h>
#include<conio.h>
class prims
{
int n,i,j,k,l,near1[50];
int cost[50][50],t[50][50];
int min, mincost;
public:
void getdata();
void prim(int,int);
void display();
};
void main()
{
prims pr;
clrscr();
pr.getdata();
pr.display();
getch();
}
void prims::getdata()
{
min=9999;
cout<<"\nPRIMS ALGORITHM\n";
cout<<"\nEnter the number of elements:";
cin>>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)
{

11
cout<<"\nThe cost between "<<i<<" and "<<j<<" : ";
cin>>cost[i][j];
cost[j][i]=cost[i][j];
if(cost[i][j]<min)
{
min=cost[i][j];
k=i;
l=j;
}
}
else
{
cost[i][j]=9999;
}
}

}
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];
}
}
prim(k,l);
}
void prims::prim(int k, int l)
{
mincost=cost[k][l];
t[1][1]=k;
t[1][2]=l;
for(i=1;i<=n;i++)
{

12
if(cost[i][l]<cost[i][k])
{
near1[i]=l;
}
else
{
near1[i]=k;
}
}
near1[l]=0;
near1[k]=0;
for(i=2;i<n;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;
for(k=1;k<=n;k++)
{
if((near1[k]!=0)&&(cost[k][near1[k]]>cost[k][j]))
{
near1[k]=j;
}
}
}

13
}
void prims::display()
{
cout<<"\n\nMinimum Cost is : "<<mincost;
cout<<"\n\nThe Minimum Spanning Tree is : \n\n";
for(i=1;i<n;i++)
{
cout<<t[i][1]<<" -> "<<t[i][2]<<"\n";
}
}

14
OUTPUT

15
RESULT
Thus, the program for minimum spanning tree using Prims algorithm was executed
successfully.

16
Expt. No: 4 IMPLEMENTATION OF KRUSKALS ALGORITHM Date:

AIM
To write a C++ program to implement Minimum spanning tree using Kruskals algorithm

ALGORITHM
Step 1: Start the program
Step 2: Declare the variables
Step 3: Enter the number of vertices.
Step 4: Set the visited[i]=0 for all vertices that initially all the nodes as unvisited node
Step 5: Choose any vertex,so that the selected vertex is the root of minimum spanning tree.
Step 6: Set the initial distance as infinity, for each and every vertex enter the corresponding
edge and its distance. If no direct connection between edges enter the weight as infinity that
is 9999
Step 7: Display the distance matrix for all vertex.
Step 8: To find the shortest path set the initial root vertex as visited.
(a) Find a lightest edge from visited to other vertex.
(b) If vertex with less distance is found add this edge to minimum spanning tree so
that it doesn’t create a cycle and repeat step 8 (a)until all the vertex are visited.
Step 9: If all the nodes are visited then display the shortest path between the nodes visited
as minimum spanning tree.
Step 10: Display the result.
Step 11: Stop the program

17
PROGRAM
#include<iostream.h>
#include<conio.h>
class kruskals
{
int parent[10],cost[10][10],t[10][10],x[20],y[20],z[20];
int n,mincost,u,v,i,r,temp,n1,j,k;
public:
void getdata();
void sort(int);
void kruskal(int,int);
int find1(int);
void union1(int,int);
void display(int);
};
void main()
{
kruskals kr;
clrscr();
kr.getdata();
getch();
}
void kruskals::getdata()
{
int n; k=1;
cout<<"\nKRUSKALS ALGORITHM\n";
cout<<"\nEnter the number of nodes : ";
cin>>n;
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<<" : ";

18
cin>>cost[i][j];
cost[j][i]=cost[i][j]; if((i<j)&&(cost[i][j]!=0))
{
x[k]=i;
y[k]=j;
z[k]=cost[i][j];
k++;
}
}
}
sort(k);
kruskal(n,k);
display(n);
}
void kruskals::sort(int k)
{
for(i=1;i<k;i++)
{
for(j=2;j<k;j++)
{
if((i<j)&&(z[i]>z[j]))
{
temp=z[i];z[i]=z[j];z[j]=temp;
temp=x[i];x[i]=x[j];x[j]=temp;
temp=y[i];y[i]=y[j];y[j]=temp;
}
}
}
}
void kruskals::kruskal(int n,int k)
{
n1=k-1; for(i=1;i<=n;i++)
{
parent[i]=-1;

19
}
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];
union1(j,k);
}
r++;
}
}
int kruskals::find1(int i)
{
while(parent[i]>=0)
{
i=parent[i];
}
return i;
}
void kruskals::union1(int x1,int x2)
{
parent[x1]=x2;
}
void kruskals::display(int n)
{
cout<<"\nMINIMUM SPANNING TREE\n\n";

20
for(i=1;i<n;i++)
{
cout<<"\t"<<t[i][1]<<"->"<<t[i][2];
}
cout<<"\n\n Minimum Cost is = "<<mincost;
getch();
}

21
OUTPUT

RESULT
Thus, the program for minimum spanning tree using Kruskals algorithm was executed
successfully.

22
Expt. No: 5 IMPLEMENTATION OF DIJIKSTRA'S ALGORITHM Date:

AIM
To write a C++ program to implement shortest source path using Dijikstra’s algorithm.

ALGORITHM
Step 1: Start the program
Step 2: Declare the variables
Step 3: Enter the number of vertices.
Step 4: Set the cost to zero for our initial node and to infinity or maximum value for all other
nodes.
Step 5: For each edge between nodes enter the cost and for nodes which do not have direct
edge as set as value 1000
Step 6: Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited
nodes called the unvisited set consisting of all the nodes.
Step 7: Display the cost matrix .Enter the source vertex
Step 8: For the current node, consider all of its unvisited neighbors and calculate their tentative
distances. Compare the newly calculated tentative distance to the current assigned value and
assign the smaller one
Step 9: When we are done considering all of the neighbors of the current node, mark the current
node as visited and remove it from the unvisited set. A visited node will never be checked
again.
Step 10: If the destination node has been marked visited or if the smallest tentative distance
among the nodes in the unvisited set is infinity then stop.
Step 11: Select the unvisited node that is marked with the smallest tentative distance, and set
it as the new "current node" then go back to step 8.
Step 12: Display the possible shortest distance from the source vertex
Step 13: Stop the program

23
PROGRAM
#include<iostream.h>
#include<conio.h>
class path
{
private:
int i,j,min,n,cost[10][10],dist[10],v;
int u,v,w,num,s[10];
public:
void getdata();
void spath();
void display();
void distance();
};
void path::getdata()
{
cout<<"\n**** 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<<" : ";

24
cin>>cost[i][j];
}
}
}
}
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;num++)
{
min=9999; for(j=1;j<=n;j++)
{
if((s[j]==0)&&(min>dist[j]))
{
min=dist[j];

25
u=j;
}
}
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();
}

26
OUTPUT

27
RESULT
Thus, the program for shortest source path using dijikstra's algorithm was executed
successfully.

28
Expt. No: 6 IMPLEMENTATION OF BINARY SEARCH Date:

AIM
To write a C++ program to implement Binary search using divide and conquer

ALGORITHM
Step 1: Start the program.
Step 2: Declare the variables and an array of elements.
Step 3: Read the value of number of elements to be stored in the array.
Step 4: Read the values of the elements of the array.
Step 5: Divide the array of elements into two which gives a middle element.
Step 6: Get the element to be searched in the array.
Step 7: Compare the element with the middle element. If the element to be searched is the
middle element stop searching and print the position.
Step 8: If the element is lesser than the middle element the searching proceeds with the first
half of the array.
Step 9: If the element is greater than the middle element the searching proceeds with the
second half of the array.
Step 10: If the element is not present in the array print” Unsuccessful search”.
Step 11: If the element is present in the array, print the position of the searched element.
Step 12: Stop the program.

29
PROGRAM
#include<iostream.h>
#include<conio.h>
#include<math.h>
class binary
{
int i,mid,low,high,n,x,a[20];
public:
void get();
int search();
};
void main()
{
int index;
binary b;
clrscr();
b.get();
index = b.search();
if(index != -1)
{
cout<<"\nElement found in "<< index+1 <<" position";
}
else
{
cout<<"\nElement not found ";
}
getch();
}
void binary::get()
{
cout<<"\nEnter the number of elements :"; cin>>n;
cout<<"\nEnter the array elements:\n"; for(i=0;i<n;i++)
{
cin>>a[i];

30
}
cout<<"\nEnter search elements:\n"; cin>>x;
}
int binary::search()
{
low=0;high=n-1; while (low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
{
return mid;
}
else if(x>a[mid])
{
low=mid+1;
}
else if(x<a[mid])
{
high=mid-1;
}
}
return -1;
}

31
OUTPUT

RESULT
Thus, the program for binary search was executed successfully

32
Expt. No: 7 IMPLEMENTATION OF TRAVELING SALESMAN PROBLEM
Date:

AIM
To write a C++ program to implement traveling salesman problem using Dynamic
Programming.

ALGORITHM
Step 1: Start the program
Step 2: Get the number of cities and cost matrix
Step 3: Assign the 1 to tour [i]
Step 4: Call the function tspdp
Step 5: In that function find the minimum cost of the graph by dynamic programming
technique
Step 6: Return the min cost
Step 7: Print the cost and path
Step 8: Stop the program

33
PROGRAM
#include<iostream.h>
#include<conio.h>
#define max 100
#define infinity 999
int tspdp(int c[][max], int tour[], int start, int n);
int main()
{
clrscr();
int n;
int i,j,c[max][max];
int tour[max],cost;
cout<<"Travelling Sales Problem using Dynamic Programming\n";
cout<<"\n Enter number of cities traverse:";
cin>>n;
cout<<"\nEnter cost matrix\n"<<endl;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
cin>>c[i][j];
if(c[i][j]==0)
c[i][j]=999;
}
for(i=0;i<n;i++)
tour[i]=i;
cost=tspdp(c,tour,0,n);
cout<<"Minimum cost"<<cost<<endl;
cout<<"Tour\n";
for(i=0;i<n;i++)
cout<<tour[i]+1<<".";
cout<<"1\n";
getch();

34
return 0;
}
int tspdp(int c[][max],int tour[],int start,int n)
{
int i,j,temp[max],mintour[max];
int mincost,cost;
if(start==n-2)
return c[tour[n-2]][tour[n-1]]+c[tour[n-1]][0];
mincost=infinity;
for(i=start+1;i<n;i++)
{
for(j=0;j<n;j++)
temp[j]=tour[j];
temp[start+1]=tour[i];
temp[i]=tour[start+1];
if(c[tour[start]][tour[i]]+(cost=tspdp(c,temp,start+1,n))<mincost)
{
mincost=c[tour[start]][tour[1]]+cost;
for(int k=0;k<n;k++)
mintour[k]=temp[k];
}
}
for(i=0;i<n;i++)
tour[i]=mintour[i];
return mincost;
}

35
OUTPUT

RESULT
Thus, the program for travelling salesman problem using dynamic programming was
executed successfully.

36
Expt. No: 8 IMPLEMENTATION OF N QUEEN PROBLEM Date:

AIM
To write a C++ program to implement N Queen Problem using backtracking.

ALGORITHM

Step 1: Start the program


Step 2: the necessary variables and Initialize x array to zero and start by placing the first queen
in k=1 in the first row.
Step 3: To find the column position start from value 1 to n, where ‘n’ is the no. Of columns or
no. Of queens.
Step 4: If k=1 then x (k)=1.so (k,x(k)) will give the position of the k th queen. Here we have to
check whether there is any queen in the same column or diagonal.
Step 5: For this considers the previous position, which had already, been found out. Check
whether for the same diagonal
X(I)=X(k) for column |X(i)-X(k)|=(I-k).
Step 6: If any one of the conditions is true then return false indicating that k th queen can’t be
placed in position X (k).
Step 7: For not possible condition increment X (k) value by one and precede d until the position
is found.
Step 8: If the position X (k)< n and k=n then the solution is generated completely.
Step 9: If k<n, then increment the ‘k’ value and find position of the next queen.
th
Step 10: If the position X (k)>n then k queen cannot be placed as the size of the matrix is
‘N*N’. So decrement the ‘k’ value by one i.e. we have to back track and after the position of
the previous queen.
Step 11: Display the possible solution
Step 12: Stop

37
PROGRAM
#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 value for n :";
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";
for(int j=1;j<=n;j++)
{
cout<<"\n";
cout<<"\n Queen "<<j<<"\t"<<x[j];
}

38
}
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;
clrscr();
queen q;
q.get();
getch();
}

39
OUTPUT

RESULT
Thus, the program for N Queens’s problem was executed successfully.

40
Expt. No: 9 IMPLEMENTATION OF SUM OF SUBSET Date:

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

ALGORITHM
Step 1: Start the program
Step 2: Declare the necessary variables
Step 3: Maintain an array X to represent all elements in the set.
Step 4: The value of Xi indicates whether the weight Wi is included or not.
Step 5: Sum is initialized to 0 i.e., s=0. Check starting from the first node and Assign X(k)<-
1.
Step 6: If S+X(k)=M then we print the subset because the sum is the required output.
Step 7: If the above condition is not satisfied then we have to check S+X(k)+W(k+1)<=M. If
so, we have to generate the left sub tree.
Step 8: After generating the left sub tree we have to generate the right sub tree, for this we
have to check S+W(k+1)<=M. Because W(k) is omitted and W(k+1) has to be selected.
Step 9: Repeat the process and find all the possible combinations of the subset.
Step 10: Display the final solution
Step 11: Stop the program

41
PROGRAM
#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];
}
}
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)

42
{
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]);
}
}
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();
}

43
OUTPUT

RESULT
Thus, the program for sum of subsets using backtracking was executed successfully.

44
Expt. No: 10 IMPLEMENTATION OF GRAPH COLORING Date:

AIM
To write a C++ program to implement Graph Coloring.

ALGORITHM
Step 1: Start the program.
Step 2: Initialize the variables n, x [20], i, j, g[20][20].
Step 3: In get (), get the number of vertices of the graph and also the adjacency edge, for I=1
to n-1 and for j=1 to n , get the g[i][j].
Step 4: First one chromatic number is assigned ,after assigning a number for ‘k’ node, we have
to check whether the adjacent nodes has got the same values if so then we have to assign the
next value.
Step 5: In mcolor (int k), do next value (k) and if(x[k]==0) , break and if(k==n), for(i=1 to n)
print the solution.
Step 6: In next value (int k), x[k]=(x[k+1]%[m+1]), if(x[k]==0) then return.
Step 7: Repeat the procedure until all possible combinations of colors are found.
Step8: The function which is used to check the adjacent nodes and same color is For j=1 to n,
if ((g[k][j]!=0)&&(x[k]==x[j])), then break and if(j==n+1) the return.
Step 9: Stop

45
PROGRAM
#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);
}gc;
void main()
{
clrscr();
gc.get();
getch();
}
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;

46
cout<<"Solutions are: \n";
mcolor(1);
}
void graph::mcolor(int k)
{
do
{
nextvalue(k);
if(x[k]==0)
{
break;
}
if(k==n)
{
for(i=1;i<=n;i++)
{
cout<<"\t"<<x[i]<<"\t";
}
cout<<"\n";
}
else
{
mcolor(k+1);
}
} while(1);
}
void graph::nextvalue(int k)
{
do
{
x[k]=(x[k]+1)%(m+1);
if(x[k]==0)
{
return;

47
}
for(j=1;j<=n;j++)
{
if((g[k][j]!=0)&&(x[k]==x[j]))
{
break;
}
}
if(j==n+1)
{
return;
}
}while(1);
}

48
OUTPUT

RESULT
Thus, the program for graph coloring was executed successfully.

49
Expt. No: 11 IMPLEMENTATION OF KNAPSACK USING BRANCH AND
Date: BOUND

AIM
To write a C program to implement Knapsack using branch and bound.

ALGORITHM
Step 1: Start the program.
Step 2: All the data are initialized.
Step 3: Get the number of items and get the weight and profit for n- items.
Step 4: Calculate unit [i] and sort the data according to the unit.
Step 5: Calculate the bound function for each node.
Step 6: Compare the current profit and weight with final profit and weight.
Step 7: If k==n show that result, else call the knapsack
Step 8: If current profit greater than final profit then interchange
Step 9: Stop the program.

50
PROGRAM
#include <stdio.h>
#include <conio.h>
#define max 10
int w[max],i,j,p[max];
int n,m;
float unit[max];
int y[max],x[max],fp=-1,fw;
void get()
{
printf(“\n Enter total number of items:”);
scanf(“%d”,&n);
printf(“\n Enter the Maximum capacity of the Sack:”);
scanf(“%d”,&m);
for(i=0;i<n;i++)
{
printf(“\n Enter the weight of the item # %d :”,i+1);
scanf(“%d”,&w[i]);
printf(“\n Enter the profit of the item # %d :”, i+1);
scanf(“%d”, &p[i]);
}
}
void show()
{
float s=0.0;
printf(“\n\tItem\tWeight\tCost\tUnit Profit\tSelected”);
for(i=0;i<n;i++)
printf(“\n\t%d\t%d\t%d\t%f\t%d”,i+1,w[i],p[i],unit[i],x[i]);
printf(“\n\n The Sack now holds following items :”);
for(i=0;i<n;i++)
if(x[i]==1)
{
printf(“%d\t”,i+1);
s += (float) p[i] * (float) x[i];
}
printf(“\n Maximum Profit: %f ”,s);
}
void sort()
{
int t,t1;
float t2;
for(i=0;i<n;i++)
unit[i] = (float) p[i] / (float) w[i];

51
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(unit[i] < unit[j])
{
t2 = unit[i];
unit[i] = unit[j];
unit[j] = t2;
t = p[i];
p[i] = p[j];
p[j] = t;
t1 = w[i];
w[i] = w[j];
w[j] =t1;
}
}
}
}
float bound(float cp,float cw,int k)
{
float b = cp;
float c = cw;
for(i=k;i<=n;i++)
{
c = c+w[i];
if( c < m)
b = b +p[i];
else
return (b+(1-(c-m)/ (float)w[i])*p[i]);
}
return b;
}
void knapsack(int k,float cp,float cw)
{
if(cw+w[k] <= m)
{
y[k] = 1;
if(k <= n)
knapsack(k+1,cp+p[k],cw+w[k]);
if(((cp+p[k]) > fp) && ( k == n))
{
fp = cp+p[k];

52
fw = cw+w[k];
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
if(bound(cp,cw,k) >= fp)
{
y[k] = 0;
if( k <= n)
knapsack(k+1,cp,cw);
if((cp > fp) && (k == n))
{
fp = cp;
fw = cw;
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
}
void main()
{
clrscr();
printf(“\n\n\n\t\t ******** KNAPSACK PROBLEM ********”);
printf(“\n\t\t —————————————–”);
get();
printf(“\n The Sack is arranged in the order…\n”);
sort();
knapsack(0,0.0,0.0);
show();
getch();
}

53
OUTPUT

RESULT
Thus, the program for knapsack using branch and bound was executed successfully.

54
55

You might also like