0% found this document useful (0 votes)
12 views

Ada Manual

The document outlines Kruskal's Algorithm for computing the minimum spanning tree (MST) in a connected weighted graph, emphasizing its greedy nature and efficiency of O(|E| log |E|). It details the algorithm's steps, including edge selection and tree merging, and provides C/C++ program implementations for various graph algorithms, including Prim's algorithm, Floyd's algorithm, and Dijkstra's algorithm. The document also includes the mission and vision of the Department of Information Science and Engineering, focusing on developing competent professionals and fostering collaboration for educational and research needs.

Uploaded by

Renuka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Ada Manual

The document outlines Kruskal's Algorithm for computing the minimum spanning tree (MST) in a connected weighted graph, emphasizing its greedy nature and efficiency of O(|E| log |E|). It details the algorithm's steps, including edge selection and tree merging, and provides C/C++ program implementations for various graph algorithms, including Prim's algorithm, Floyd's algorithm, and Dijkstra's algorithm. The document also includes the mission and vision of the Department of Information Science and Engineering, focusing on developing competent professionals and fostering collaboration for educational and research needs.

Uploaded by

Renuka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Aim :

To apply Kruskal's Algorithm for computing the minimum spanning tree is directly basedon the generic MST
algorithm. It builds the MST in forest.
Definition:

Kruskal’s algorithm is an algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. This mean it finds a subset of the edges that forms a tree that includes
everyvertex, where the total weight of all the edges in the tree is minimized. If the graph is not
connected,then it finds a minimum spanning forest .It is an example of a greedy algorithm
.

Efficiency:With an efficient sorting algorithm,the time efficiency of Kruskal’s algorithm will be


inO(│E│log│E│)

Algorithm

Start with an empty set A, and select at every stage the shortest edge that has not been chosen
orrejected, regardless of where this edge is situated in graph.
•Initially, each vertex is in its own tree in forest.
•Then, algorithm consider each edge in turn, order by increasing weight.
•If an edge (u, v) connects two different trees, then (u,v) is added to the set of edges of theMST, and
two trees connected by an edge (u,v) are merged into a single tree.
•On the other hand, if an edge (u,v) connects two vertices in the same tree, then edge (u,v) is
discarded.Kruskals algorithm can be implemented using
disjoint set data structure or priority queue data structure.
I Kruskal's algorithm implemented with disjoint-sets data structure.
MST_KRUSKAL (G, w)

1.A ← {}
// A will ultimately contains the edges of the MST2.

for each vertex v in V[G]3.


do Make_Set (v )4.
Sort edge of E by nondecreasing weights w5.

for each edge (u,v ) in E


6.do if FIND_SET (u) ≠ FIND_SET (v )
7. then A = AU{(u,v )}
8.UNION (u,v )
9.Return A
Program:#include<stdio.h>

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING


Mission
“The department aims to develop the best information science professionals who
work creatively, communicate effectively and become technologically competent,
also to mould them into good citizens by inculcating sense of ethical values in them”

Vision
“To meet the educational, research and service needs of the region through
collaboration with academic and technical institutions, business and governmentagencies and
cultural organizations, thereby providing a platform that encouragesstudents and staff to
Continue their intellectual and professional growth”

INDEX

1.
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
givenconnected undirected graph using Kruskal's algorithm.

2.Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
givenconnected undirected graph using Prim's algorithm.

3.a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem
usingFloyd's algorithm. b. Design and implement C/C++ Program to find the transitive
closureusing Warshal's algorithm.

4.Design and implement C/C++ Program to find shortest paths from a given vertex in aweighted
connected graph to other vertices using Dijkstra's algorithm.

5.Design and implement C/C++ Program to obtain the Topological ordering of vertices in agiven
digraph

6.Design and implement C/C++ Program to solve 0/1 Knapsack problem using
DynamicProgramming method.

7.Design and implement C/C++ Program to solve discrete Knapsack and continuousKnapsack
problems using greedy approximation method.

8.Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn}of n
positive integers whose sum is equal to a given positive integer d.

9.Design and implement C/C++ Program to sort a given set of n integer elements usingSelection
Sort method and compute its time complexity. Run the program for variedvalues of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versusn. The elements can be read
from a file or can be generated using the random numbergenerator.
10Design and implement C/C++ Program to sort a given set of n integer elements usingQuick
Sort method and compute its time complexity. Run the program for varied valuesof n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. Theelements can be read
from a file or can be generated using the random numbergenerator.

11.Design and implement C/C++ Program to sort a given set of n integer elements usingMerge
Sort method and compute its time complexity. Run the program for varied valuesof n> 5000, and
record the time taken to sort. Plot a graph of the time taken versus n.The elements can be read
from a file or can be generated using the random numbergenerator.

12Design and implement C/C++ Program for N Queen's problem using Backtracking.

1.

Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
givenconnected undirected graph using Kruskal's algorithm.

Aim :
To apply Kruskal's Algorithm for computing the minimum spanning tree is directly basedon the generic MST
algorithm. It builds the MST in forest.
Definition:

Kruskal’s algorithm is an algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. This mean it finds a subset of the edges that forms a tree that includes
everyvertex, where the total weight of all the edges in the tree is minimized. If the graph is not
connected,then it finds a minimum spanning forest .It is an example of a greedy algorithm
.

Efficiency:With an efficient sorting algorithm,the time efficiency of Kruskal’s algorithm will be


inO(│E│log│E│)

Algorithm

Start with an empty set A, and select at every stage the shortest edge that has not been chosen
orrejected, regardless of where this edge is situated in graph.
•Initially, each vertex is in its own tree in forest.
•Then, algorithm consider each edge in turn, order by increasing weight.
•If an edge (u, v) connects two different trees, then (u,v) is added to the set of edges of theMST, and
two trees connected by an edge (u,v) are merged into a single tree.
•On the other hand, if an edge (u,v) connects two vertices in the same tree, then edge (u,v) is
discarded.Kruskals algorithm can be implemented using disjoint set data structure or priority queue
datastructure.I Kruskal's algorithm implemented with disjoint-sets data structure.
MST_KRUSKAL (G, w)
1.A ← {}
// A will ultimately contains the edges of the MST2.

for each vertex v in V[G]


3.do Make_Set (v )
4.Sort edge of E by nondecreasing weights w
5.for each edge (u,v ) in E
6.do if FIND_SET (u) ≠ FIND_SET (v )
7. then A = AU{(u,v )}
8.UNION (u,v )
9.Return AProgram:#include<stdio.h>

#define INF 999


#define MAX 100
int p[MAX],c[MAX][MAX],t[MAX][2];
int find(int v){while(p[v])v=p[v];
return v;
}
void union1(int i,int j)
{p[j]=i;
}
void kruskal(int n)
{int i,j,k,u,v,min,res1,res2,sum=0;for(k=1;k<n;k++)
{min=INF;for(i=1;i<n-1;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
continue;
if(c[i][j]<min)
{
u=find(i);
v=find(j);
if(u!=v)
{
res1=i;
res2=j;
min=c[i][j];
}
}
}
}
union1(res1,find(res2));
t[k][1]=res1;
t[k][2]=res2;
sum=sum+min;
}
printf("\nCost of spanning tree is=%d",sum);
printf("\nEdgesof spanning tree are:\n");

for(i=1;i<n;i++)
printf("%d -> %d\n",t[i][1],t[i][2]);
}
int main()
{
int i,j,n;
printf("\nEnter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)p[i]=0;
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
kruskal(n);
return 0;
}
Input/Output:
Enter the n value:5
Enter the graph data:
0 10 15 9 999
10 0 999 17 15
15 999 0 20 999
9 17 20 0 18
999 15 999 18 0
Cost of spanning tree is=49
Edgesof spanning tree are:
1 -> 4
1 -> 2
1 -> 3
2 -> 5

Program 2
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
givenconnected undirected graph using Prim's algorithm.
Aim:
To find minimum spanning tree of a given graph using prim’s algorithm

Definition:
Prim’s is an algorithm that finds a minimum spanning tree for a connected weighted
undirected graph. This means it finds a subset of the edges that forms a tree that includes every
vertex,
where the total weight of all edges in the tree is minimized. Prim’
s algorithm is an example of a greedyalgorithm.
Algorithm

MST_PRIM (G,w, v)

1.Q ← V[G]
2.for each u in Q do
3.key [u] ←∞
4.key [r ] ← 0
5.π[r ] ← NIl
6.while queue is not empty do
7.u← EXTRACT_MIN (Q)
8.for each v in Adj[u] do
9.if v is in Q and w (u,v ) < key [v ]
10.then π[v ] ←w (u,v )
11.key [v ] ←w (u,v )

Analysis

The performance of Prim's algorithm depends of how we choose to implement the priority
queueQ.

Program:
#include<stdio.h>
// #include<conio.h>
#define INF 999
int prim(int c[10][10],int n,int s)
{
int v[10],i,j,sum=0,ver[10],d[10],min,u;
for(i=1;i<=n;i++)
{
ver[i]=s;
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n-1;i++)
{
min=INF;
for(j=1;j<=n;j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
sum=sum+d[u];
printf("\n%d -> %d sum=%d",ver[u],u,sum);

for(j=1;j<=n;j++)
if(v[j]==0 && c[u][j]<d[j])
{
d[j]=c[u][j];
ver[j]=u;
}
}
return sum;
}
void main()
{
int c[10][10],i,j,res,s,n;
clrscr();
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce node:");
scanf("%d",&s);
res=prim(c,n,s);
printf("\nCost=%d",res);
getch();
}

Input/output:
Enter n value:3
Enter the graph data:
0 10 1
10 0 6
160
Enter the souce node:11 -> 3
sum=1
3 -> 2 sum=7
Cost=7
Program 3
a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd'salgorithm. b. Design and implement C/C++ Program to find the transitive closure using
Warshal'salgorithm.

Definition:
The
Floyd algorithm
is a graph analysis algorithm for finding shortest paths in a weightedgraph (with positive or
negative edge weights). A single execution of the algorithm will find the lengths(summed
weights) of the shortest paths between
all
pairs of vertices though it does not return details ofthe paths themselves. The algorithm is an
example of dynamic programming
Algorithm:Floyd’s Algorithm
Accept no .of vertices
Call graph function to read weighted graph
// w(i,j)
Set D[ ] <- weighted graph matrix // get D {d(i,j)} for k=0
// If there is a cycle in graph, abort. How to find?
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
D[i,j] = min {D[i,j], D[i,k] + D[k,j]}
Print D
Program A:
#include<stdio.h>
#include<conio.h>
#define INF 999
int min(int a,int b)
{
return(a<b)?a:b;
}
void floyd(int p[][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
void main()
{
int a[10][10],n,i,j;
clrscr();
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
floyd(a,n);
printf("\nShortest path matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}

Input/Output:
Enter the n value:4
Enter the graph data:0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0
Shortest path matrix
0 10 3 4
2056
7701
6 16 9 0

Definition
:The Floyd-Warshall algorithm is a graph analysis algorithm for finding shortest paths in
aweighted graph. A single execution of the algorithm will find the lengths of the shortest path
betweenall pairs of vertices though it does not return details of the paths themselves. The
algorithm is anexample of Dynamic programming.
Algorithm
//Input: Adjacency matrix of digraph
//Output: R, transitive closure of digraph
Accept no .of vertices
Call graph function to read directed graph
Set R[ ] <- digraph matrix
// get R {r(i,j)} for k=0
Print digraph
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
R(i,j) = 1 if
{rij(k-1) = 1 OR rik(k-1) = 1 and r kj(k-1)= 1}
Print R

Program:
#include<stdio.h>
void warsh(int p[][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=p[i][j] || p[i][k] && p[k][j];
}
int main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
warsh(a,n);
printf("\nResultant path matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
Input/Output:
Enter the n value:4
Enter the graph data:
0100
0001
0000
1010
Resultant path matrix
1111
1111
0000
1111

Program 4
Design and implement C/C++ Program to find shortest paths from a given vertex in aweighted
connected graph to other vertices using Dijkstra's algorithm.
Aim:To find shortest path using Dijikstra’s algorithm.
Definition
: Dijikstra’s algorithm
-For a given source vertex(node) in the graph, the algorithm finds thepath with lowest cost
between that vertex and every other vertex. It can also be used for finding cost ofshortest paths
from a single vertex to a single destination vertex by stopping the algorithm once theshortest
path to the destination vertex has been determined.
Efficiency:1)2)-graph represented by weighted matrix and priority queue as unordered array
2)O(│E│log│v│)-graph represented by adjacency lists and priority queue as min-heap

Algorithm: Dijikstra(G,s)
//Dijikstra’s algorithm for single source shortest path
//input:A weighted connected graph with non negative weights and its vertex s
//output:The length dv of a shortest path from s to v and penultimate vertex pv for every vertex v
in V
Initialize(Q)for every vertex v in V do
dv<-∞;
Pv<-null
Insert(Q,v,dv)
Ds<-0;
Decrease(Q,s,ds);
VT<-ǿ
for i<-0 to │V│-1 do
u*<-DeleteMin(Q)
VT<-VT U{u*}
For every vertex u in V-VT that is adjacent to u*do
If du*+w(u*,u)<du
du<- du*+w(u*,u);
Pu<-u* Decrease(Q,u,du)

Program:
#include<stdio.h>
#define INF 999
void dijkstra(int c[10][10],int n,int s,int d[10])
{
int v[10],min,u,i,j;
for(i=1;i<=n;i++)
{
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n;i++)
{
min=INF;
for(j=1;j<=n;j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
for(j=1;j<=n;j++)
if(v[j]==0 && (d[u]+c[u][j])<d[j])
d[j]=d[u]+c[u][j];
}
}
int main()
{
int c[10][10],d[10],i,j,s,sum,n;
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce node:");
scanf("%d",&s);
dijkstra(c,n,s,d)

for(i=1;i<=n;i++)
printf("\nShortest distance from %d to %d is %d",s,i,d[i]);
return 0;
}

Input/Output
Enter n value:6
Enter the graph data:0 15 10 999 45 999
999 0 15 999 20 999
20 999 0 20 999 999
999 10 999 0 35 999
999 999 999 30 0 999
999 999 999 4 999 0
Enter the souce node:2
Shortest distance from 2 to 1 is 35
Shortest distance from 2 to 2 is 0
Shortest distance from 2 to 3 is 15
Shortest distance from 2 to 4 is 35
Shortest distance from 2 to 5 is 20
Shortest distance from 2 to 6 is 999
Output:
enter the no. of nodes:
6
enter the cost adjacency matrix,'9999' for no direct path
0 15 10 9999 45 9999
9999 0 15 9999 20 9999
20 9999 0 20 9999 9999
9999 10 9999 0 35 9999
9999 9999 9999 30 0
9999 9999 9999 9999 4 9999 0

enter the starting vertex:6

Shortest path from starting vertex to other vertices are

6 ->1=49
6 ->2=14
6 ->3=29
6->4=4
6->5=34
6->6=0

Program 5
Design and implement C/C++ Program to obtain the Topological ordering of vertices in a given
digraph
Aim:To find topological ordering of given graph
Definition:Topological ordering that for every edge in the graph,the vertex where the edge starts
is listed before the edge where the edge ends.

Algorithm:
1.repeatedly identify in a remaining digraph a source which is a vertex with no incoming edges
and delete it along with all edges outgoing from it
2.Thje order in which the vertices are deleted yields a solution to the topological sorting.

#include<stdio.h>
// #include<conio.h>
int temp[10],k=0;
void sort(int a[][10],int id[],int n)
{
int i,j;for(i=1;i<=n;i++)
{
if(id[i]==0)
{
id[i]=-1;
temp[++k]=i;
for(j=1;j<=n;j++)
{
if(a[i][j]==1 && id[j]!=-1)
id[j]--;
}
i=0;
}
}
}
void main()
{
int a[10][10],id[10],n,i,j;
// clrscr();
printf("\nEnter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
id[i]=0;
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==1)
id[j]++;
}
sort(a,id,n);
if(k!=n)
printf("\nTopological ordering not possible");
else
{
printf("\nTopological ordering is:");
for(i=1;i<=k;i++)
printf("%d ",temp[i]);
}
// getch();
}

input/output:
Enter the n value:6
Enter the graph data:
001100
000110
000101
000001
000001
000000
Topological ordering is:1 2 3 4 5 6

Program 6
Design and implement C/C++ Program to solve 0/1 Knapsack problem using
DynamicProgramming method.
Aim: To implement 0/1 Knapsack problem using Dynamic programming

Definition:using Dynamic programming


It gives us a way to design custom algorithms which systematically search all possibilities (thus
guaranteeing correctness) while storing results to avoid re computing (thus providing
efficiency).We are given a set of n items from which we are to select some number of items to be
carriedin a knapsack(BAG). Each item has both a weight and a profit . The objective is to choose
the set of itemsthat fits in the knapsack and maximizes the profit.Given a knapsack with
maximum capacity W , and a set S consisting of n items , Each item I has some weight
Wi and benefit value bi (all wi , bi and W are integer values)
Problem: How to pack the knapsack to achieve maximum total value of packed items

ALGORITHM
//(n items, W weight of sack) Input: n, Wi,,, Vi and W – all integers
//Output: V(n,W)
// Initialization of first column and first row elements
Repeat for i = 0 to n

set V(i,0) = 0
Repeat for j = 0 to W
Set V(0,j) = 0
//complete remaining entries row by row
Repeat for i = 1 to n
repeat for j = 1 to W
f ( Wi <= j ) V(i,j)) = max{ V(i-1,j), V(i-1,j-Wi) + Vi }
if ( Wi > j ) V(i,j) = V(i-1,j)
Print V(n,W)

PROGRAM:
#include<stdio.h>
int w[10],p[10],n;
int max(int a,int b)
{
return a>b?a:b;
}
int knap(int i,int m)
{
if(i==n) return w[i]>m?0:p[i];
if(w[i]>m) return knap(i+1,m);
return max(knap(i+1,m),knap(i+1,m-w[i])+p[i]);
}
int main()
{
int m,i,max_profit;
printf("\nEnter the no. of objects:");
scanf("%d",&n);
printf("\nEnter the knapsack capacity:");
scanf("%d",&m);
printf("\nEnter profit followed by weight:\n");
for(i=1;i<=n;i++)
scanf("%d %d",&p[i],&w[i]);
max_profit=knap(1,m);
printf("\nMax profit=%d",max_profit);
return 0;
}

Input/Output:
Enter the no. of objects:4
Enter the knapsack capacity:6
Enter profit followed by weight:
78 2
45 3
92 4
71 5
Max profit=170

Program 7
Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method.
This program first calculates the profit-to-weight ratio for each item, then sorts the items based
on this ratio in non-increasing order. It then fills the knapsack greedily by selecting items with
the highest ratio until the knapsack is full. If there's space left in the knapsack after selecting
whole items, it adds fractional parts of the next item. Finally, it prints the optimal solution and
the solution vector.

Here's a simplified version of the C program to solve discrete Knapsack and continuous
Knapsackproblems using the greedy approximation method:
#include <stdio.h>
#define MAX 50
int p[MAX], w[MAX], x[MAX];
double maxprofit;
int n, m, i;
void greedyKnapsack(int n, int w[], int p[], int m)
{
double ratio[MAX];
// Calculate the ratio of profit to weight for each item
for (i = 0; i < n; i++) {
ratio[i] = (double)p[i] / w[i];
}
// Sort items based on the ratio in non-increasing order
for (i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (ratio[i] < ratio[j]) {
double temp = ratio[i];
ratio[i] = ratio[j];
ratio[j] = temp;
int temp2 = w[i];
w[i] = w[j];
w[j] = temp2;
temp2 = p[i];
p[i] = p[j];
p[j] = temp2;
}
}
}
int currentWeight = 0;
maxprofit = 0.0;
// Fill the knapsack with items
for (i = 0; i < n; i++) {
if (currentWeight + w[i] <= m) {
x[i] = 1; // Item i is selected
currentWeight += w[i];
maxprofit += p[i];
}
else {
// Fractional part of item i is selected
x[i] = (m - currentWeight) / (double)w[i];
maxprofit += x[i] * p[i];
break;
}
}
printf("Optimal solution for greedy method: %.1f\n", maxprofit);
printf("Solution vector for greedy method: ");
for (i = 0; i < n; i++)
printf("%d\t", x[i]);
}
int main()
{
printf("Enter the number of objects: ");
scanf("%d", &n);
printf("Enter the objects' weights: ");
for (i = 0; i < n; i++)
scanf("%d", &w[i]);
printf("Enter the objects' profits: ");
for (i = 0; i < n; i++)
scanf("%d", &p[i]);
printf("Enter the maximum capacity: ");
scanf("%d", &m);
greedyKnapsack(n, w, p, m);
return 0;
}
Program 8
Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n
positive integers whose sum is equal to a given positive integer d.
AIM: An instance of the Subset Sum problem is a pair (S, t), where S = {x1, x2, ..., xn} is a set
of positive integers and t (the target) is a positive integer. The decision problem asks for a
subset of S whose sum isas large as possible, but not larger than t.
Algorithm: SumOfSub (s, k, r)
//Values of x[ j ], 1 <= j < k, have been determined//Node creation at level k taking place: also
call for creation at level K+1 if possible// s = sum of 1 to k-1 elements and r is sum of k to n
elements//generating left child that means including k in solution
Set x[k] = 1
f (s + s[k] = d) then subset found, print solution
If (s + s[k] + s[k+1] <=d)
then SumOfSum (s + s[k], k+1, r – s[k])
//Generate right child i.e. element k absent
If (s + r - s[k] >=d) AND (s + s[k+1] )<=d
then { x[k]=0;
SumOfSub(s, k+1, r – s[k])

Program:
#include<stdio.h>
// #include<conio.h>
#define MAX 10
int s[MAX],x[MAX],d;
void sumofsub(int p,int k,int r)
{
int i;
x[k]=1;
if((p+s[k])==d)
{
for(i=1;i<=k;i++)
if(x[i]==1)
printf("%d ",s[i]);
printf("\n");
}
else
if(p+s[k]+s[k+1]<=d)
sumofsub(p+s[k],k+1,r-s[k]);
if((p+r-s[k]>=d) && (p+s[k+1]<=d))
{
x[k]=0;
sumofsub(p,k+1,r-s[k]);
}
}
int main()
{
int i,n,sum=0;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the set in increasing order:");
for(i=1;i<=n;i++)
scanf("%d",&s[i]);
printf("\nEnter the max subset value:");
scanf("%d",&d);
for(i=1;i<=n;i++)
sum=sum+s[i];
if(sum<d || s[1]>d)
printf("\nNo subset possible");
else
sumofsub(0,1,sum);return 0;
}

Input/output:

Enter the n value:9


Enter the set in increasing order:1 2 3 4 5 6 7 8 9

Enter the max subset value:9


1 26
2 35
18
234
27
3 6
4 5
9
Program 9
Design and implement C/C++ Program to sort a given set of n integer elements using Selection
Sort method and compute its time complexity. Run the program for varied values of n> 5000and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

Aim: Sort a given set of elements using Selection sort and determine the time required to sort
elements.Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n.

Definition: selection sort is a sorting routine that scans a list of items repeatedly and, on each
pass, selects the item with the lowest value and places it in its final position. It is based on
brute force approach. Sequential search is a Θ(n 2) algorithm on all inputs.

Algorithm:SelectionSort(A[0…n-1])
//sort a given array by select5ion sort
//input:A[0…n-1]of orderable elements
Output:Array a[0…n-1]
Sorted in ascending order
for i<- 0 to n-2 do
min<-i
for j<-i+1 to n-1 do
if A[j]<A[min] min<-j
swap A[i] and A[min]

program:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<dos.h>
void selsort(int a[],int n)
{
int i,j,small,pos,temp;
for(j=0;j<n-1;j++)
{
small=a[j];

pos=j;
for(i=j+1;i<n;i++)
{
if(a[i]<small)
{small=a[i];
pos=i;
}
}
temp=a[j];
a[j]=small;
a[pos]=temp;
}
}
void main()
{
int a[10],i,n;
clock_t start,end;
float dura;
clrscr();
printf("\nEnter the n value:");
scanf("%d",&n);printf("\nEnter the array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
start=clock();
selsort(a,n);
delay(100);
end=clock();
dura=(end-start)/CLK_TCK;
printf("\nTime taken is:%f",dura);
printf("\nSorted array is:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
Input /output:
Enter the n value:5
Enter the array:10 2 3 15 12
Time taken is:0.109890
Sorted array is:2 3 10 12 15

Program 10
Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort
method and compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

Aim:The aim of this program is to sort ‘n’ randomly generated elements using Quick
sort and Plotting the graph of the time taken to sort n elements versus n.
Definition: Quick sort is based on the Divide and conquer approach. Quick sort divides array
according to their value. Partition is the situation where all the elements before some 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].

Efficiency: Cbest(n) Є Θ(n log 2 n), Cworst(n) ЄΘ(n2), Cavg(n)Є1.38 n log 2 n

Algorithm: Quick sort (A[l….r])

// Sorts a sub array by quick sort


//Input : A sub array A[l..r] of A[0..n-1] ,defined by its left and right indices l
//and r
// Output : The sub array A[l..r] sorted in non decreasing order
if l < r
s = Partition (A[l..r]) //s is a split position
Quick sort (A[l …s-1])
Quick sort (A[s+1…r])

ALGORITHM Partition (A[l…r])


//Partition a sub array by using its first element as a pivot
// Input : A sub array A[l…r] of A[0…n-1] defined by its left and right indices l and // r (l < r)
// Output : A partition of A[l…r], with the split position returned as this function’s value
p=A[l]
i=l;
j=r+1;
repeat
delay(500);
repeat i= i+1 until A[i] >= p
repeat j=j-1 until A[J] <= p
Swap (A[i],A[j])
until I >=j
Swap (A[i],A[j]) // Undo last Swap when i>= j
Swap (A[l],A[j])
Return j

Program:

#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<time.h>
void fnGenRandInput(int [], int);
void fnDispArray( int [], int);
int fnPartition(int [], int , int );
void fnQuickSort(int [], int , int );
inline void fnSwap(int*, int*);
inline void fnSwap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
/*********
*Function
: main

*Input parameters:
*int argc - no of commamd line arguments
*
char **argv - vector to store command line argumennts

*RETURNS
:0 on success*********************************************************/

int main( int argc, char **argv)

FILE *fp;
struct timeval tv;

double dStart,dEnd;
int iaArr[500000],iNum,iPos,iKey,i,iChoice;
for(;;)
{
printf("\n1.Plot the Graph\n2.QuickSort\n3.Exit");

printf("\nEnter your choice\n");


scanf("%d",&iChoice);
switch(iChoice)
{case 1:
fp fopen("QuickPlot.dat","w");
for(i=100;i<100000;i+=100)

fnGenRandInput(iaArr,i);
gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);
fnQuickSort(iaArr,0,i-1);
gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);
fprintf(fp,"%d\t%lf\n",i,dEnd-dStart);
}
fclose(fp);
printf("\nData File generated and stored in file < QuickPlot.dat >.\nUse a plotting utility\n");
break;
case 2:printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(iaArr,iNum);
fnDispArray(iaArr,iNum);
fnQuickSort(iaArr,0,iNum-1);
printf("\nSorted Array\n");
fnDispArray(iaArr,iNum);
break;
case 3:
exit(0);
}
}
return 0;
}
/
******************************************************************************
*Function:
fnPartition
*Description
: Function to partition an iaArray using First element as Pivot
*Input parameters:
*int a[] - iaArray to hold integers
*int l
- start index of the subiaArray to be sorted

*int r
- end index of the subiaArray to be sorted

*RETURNS: integer value specifying the location of


partition****************************************************************/

int fnPartition(int a[], int l, int r)

{
int i,j,temp;
int p;
p = a[l];
i = l;
j = r+1;
do
{
do { i++; } while (a[i] < p);
do { j--; } while (a[j] > p);
fnSwap(&a[i], &a[j]);
}
while (i<j);
fnSwap(&a[i], &a[j]);
fnSwap(&a[l], &a[j]);
return j;
}
/
*****************************************************************************
Function: fnQuickSort
*Description
: Function to sort elements in an iaArray using Quick Sort
*
Input parameters:
*
int a[] - iaArray to integers*

int l
- start index of the subiaArray to be sorted
*
int r
- end index of the subiaArray to be sorted
*RETURNS
: no value**************************************************************/

void fnQuickSort(int a[], int l, int r)


{
int s;
if (l < r)
{s = fnPartition(a, l, r);
fnQuickSort(a, l, s-1);
fnQuickSort(a, s+1, r);}}
/***************************************************************************
Function
: GenRandInput
*Description: Function to generate a fixed number of random elements

*Input parameters:
*
int X[] - array to hold integers
*
int n- no of elements in the array

*RETURNS
:no return
value*************************************************************************
*****/

void fnGenRandInput(int X[], int n)


{
int i;
srand(time(NULL));
for(i=0;i<n;i++)
{X[i] = rand()%10000;
}
}
/
******************************************************************************
*Function: DispArray
*Description: Function to display elements of an array

*Input parameters:
*
int X[] - array to hold integers
*
int n- no of elements in the array
*RETURNS
: no return
value*************************************************************************
*****/
void fnDispArray( int X[], int n)
{
int i;for(i=0;i<n;i++)
printf(" %5d \n",X[i]);
}

Quick.gpl

# Gnuplot script file for plotting data in file "QuickPlot.dat"


# This file is called Quick.gpl
set terminal png font arialset title "Time Complexity for quick Sort"
set autoscaleset xlabel "Size of Input"
set ylabel "Sorting Time (microseconds)"
set grid
set output "QuickPlot.png"
plot "QuickPlot.dat" t 'Quick Sort' with lines
To compile and execute:
iselab@cselab-B85M-DS3H:~/Desktop/sample$ gcc quicksort2.c
iselab@cselab-B85M-DS3H:~/Desktop/sample$ gnuplot Quick.gpl
iselab@cselab-B85M-DS3H:~/Desktop/sample$ ls
This will create the QuickPlot.png file
iselab@cselab-B85M-DS3H:~/Downloads$ gcc mergesort.c
iselab@cselab-B85M-DS3H:~/Downloads$ ./a.out
1.Plot the Graph
2.MergeSort
3.Exit
Choice 1 shows the QuickPlot.dat file which is created automatically after entering the choice 1,
this ischecked by giving ls cmd in the terminal
Enter your choice1
Data File generated and stored in file < MergePlot.dat >.
Use a plotting utility

1.Plot the Graph


2.MergeSort
3.Exit
Enter your choice
3
iselab@cselab-B85M-DS3H:~/Downloads$ lsMergePlot.dat mergesort.c, quicksort2
.cQuickPlot.dat
iselab@cselab-B85M-DS3H:~/Downloads$ gedit MergePlot.dat // to see the random
values generated
iselab@cselab-B85M-DS3H:~/Downloads$ vi MergePlot.dat

Input and output:

Enter your choice 2


Enter the number of elements to sort 10

Unsorted Array
7506
741
7150
6997
5247
2059
8915
7327
9897
9867
Sorted Array
741
2059
5247
6997
7150
7327
7506
8915
9867
9897

QuickPlot.png
Program 11
Design and implement C/C++ Program to sort a given set of n integer elements using Merge
Sort method and compute its time complexity. Run the program for varied values of n> 5000,
and record the time taken to sort. Plot a graph of the time taken versus n. The elements can be
read from a file or can be generated using the random number generator.

Aim:The aim of this program is to sort ‘n’ randomly generated elements using Merge
sort and Plotting the graph of the time taken to sort n elements versus n.

Definition: Merge sort is a sort algorithm based on divide and conquer technique. It divides the
array element based on the position in the array. The concept is that we first break the list
into two smaller lists of roughly the same size, and then use merge sort recursively on the sub
problems, until they cannot subdivide anymore. Then, we can merge by stepping through
the lists in linear time. Its time efficiency is
Θ(n log n).

Algorithm:Merge sort(A[0…n-1]// Sorts array A[0..n-1] by Recursive merge sort

You might also like