Daa Lab Manual
Daa Lab Manual
A[0]A[s-1]
All are <=A[s]
A[s]
A[s+1]A[n-1]
all are >=A[s]
Algorithm : QUICKSORT(a[l..r])
//Sorts a subarray by quicksort
//Input: A subarray A[l..r] of A[0..n-1],defined by its left and right indices l
and r //Output: Subarray A[l..r] sorted in nondecreasing order
{
if l<r
{
s Partition(A[l..r]) //s is a split
position QUICKSORT(A[l..s-1])
QUICKSORT(A[s+1..r])
}
}
Algorithm : Partition(A[l..r])
//Partition a subarray by using its first element as its pivot
//Input:A subarray 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 functions value
{
p A[l]
i l; j r+1
repeat
{ 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
}
Cworst (n) (n )
Cavg (n) 1.38nlog2n
Program:
/*To sort a set of elements using Quick sort algorithm.*/
#include<stdio.h>
#include<time.h>
#define max 500
void main()
{
int a[max],i,n;
clock_t s,e;
clrscr();
qsort(a,j+1,high);
}
}
int partition(int a[], int low,int high)
{
int pivot,i,j,temp;
pivot=a[low];
i=low+1;
j=high;
while(1)
{
while(pivot>a[i] && i<=high)
i++;
while(pivot<a[j])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
temp=a[j];
a[j]=a[low];
a[low]=temp;
return j;
}
}
}
OUTPUT
Note:
Program to be executed for various sizes of
input. Table to be filled with data
Size: n Input
4
8
16
32
Ascending
Time taken
Input
Descending
Random Order
Time taken Input
Time taken
1. Split array A[1..n] in two and make copies of each half in arrays B[1.. n/2 ] and C[1.. n/2 ]
2. Sort arrays B and C
3. Merge sorted arrays B and C into array A as follows:
a)
Repeat the following until no elements remain in one of the arrays:
i.
compare the first elements in the remaining unprocessed portions of the
arrays
ii.
copy the smaller of the two into A, while incrementing the index
indicating the unprocessed portion of that array
b)
Once all elements in one of the arrays are processed, copy the remaining
unprocessed elements from the other array into A.
{
i 0; j0; k0
while i<p and j<q do
{
if B[i] <= C[j]
A[k] B[i]; i i+1
else
A[k] C[j]; j j+1
k k+1
}
if i=p
Complexity:
All cases have same efficiency: ( n log n)
Number of comparisons is close to theoretical minimum for comparison-based
sorting: log n ! n lg n - 1.44 n
Space requirement: ( n ) (NOT in-place)
Program:
/*To sort a set of elements using Merge sort algorithm.*/
#include "stdafx.h"
#include<omp.h>
#include<time.h>
#include<stdio.h>
#include<iostream>
#include<conio.h>
#define max 100
void mergesort(int[100],int,int);
void merge(int[100],int,int,int);
int a[max];
void main()
{
int i,n;
clock_t s,e;
printf("%d\t",a[i]);
printf("\nthe time taken=%f\n",(es)/CLK_TCK); getch();
}
if(h>mid)
{
#pragma omp parallel for
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=low;k<=high;k++)
a[k]=b[k];
}
OUTPUT
Note:
Program to be executed for various sizes of input.
Fill the given table. Obtaining a constant value in the column time taken would
prove that the complexity of merge sort is same in all case.
Size: n Input
4
8
16
32
Ascending
Time taken
Input
Descending
Random Order
Time taken Input
Time taken
1) Find the vertices whose indegree is zero and place them on the stack
2) Pop a vertex u and it is the task to be done
3) Add the vertex u to the solution vector
4) Find the vertices v adjacent to vertex u. The vertices v represents the jobs which
depend on job u
5) Decrement indegree[v] gives the number of depended jobs of v are reduced by one.
Algorithm topological_sort(a,n,T)
//purpose :To obtain the sequence of jobs to be
executed resut In topolocical order
// Input:a-adjacency matrix of the given
graph //n-the number of vertices in the
graph //output:
// T-indicates the jobs that are to be executed in the order
For j<-0 to n-1
do Sum-0
For i<- 0to n-1 do
Sum<-sum+a[i][j]
End for
Top -1
For i<- 0 to n-1 do
If(indegree [i]=0)
Top <-top+1
S[top]<- i
End if End
for While
top!= 1 u<s[top] top<top-1
Add u to solution vector T
For each vertex v adjacent to u
Decrement indegree [v] by one
If(indegree
[v]=0) Top<top+1 S[top]<-v
End if
End for
End while
Write T
return
Program:
/*To obtain the topological order in of vertices in a digraph.*/
#include<stdio.h>
void findindegree(int [10][10],int[10],int);
void topological(int,int [10][10]);
void main()
{
int a[10][10],i,j,n;
clrscr();
printf("Enter the number of
nodes:"); scanf("%d",&n);
printf("\nEnter the adjacency
matrix\n"); for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\nThe adjacency matirx
is:\n"); for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
topological(n,a);
getch();
}
void findindegree(int a[10][10],int indegree[10],int n)
{
int i,j,sum;
for(j=1;j<=n;j++)
{
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+a[i][j];
}
indegree[j]=sum;
}
}
void topological(int n,int a[10][10])
{
int k,top,t[100],i,stack[20],u,v,indegree[20];
k=1;
top=-1;
findindegree(a,indegree,n);
for(i=1;i<=n;i++)
{
if(indegree[i]==0)
{
stack[++top]=i;
}
}
while(top!=-1)
{
u=stack[top-]; t[k++]=u;
for(v=1;v<=n;v++)
{
if(a[u][v]==1)
{
indegree[v]--;
if(indegree[v]==0)
{
stack[++top]=v;
}
}
}
}
printf("\nTopological sequence
is\n"); for(i=1;i<=n;i++)
printf("%d\t",t[i]);
}
OUTPUT:
Algorithm Warshall(A[1..n,1..n])
//Implements Warshalls algorithm for computing the transitive
closure //Input: The Adjacency matrix A of a digraph with n vertices
//Output: The transitive closure of digraph
{
(0)
R A
for k 1 to n do
{
for i 1 to n do
{
for j 1 to n do
{
(k)
(k-1)
(k-1)
(k-1)
R [i,j] R
[i,j] or R
[i,k] and R
[k,j]
}
}
}
(n)
return R
}
Program:
/*Compute the transitive closure of a given directed graph using Warshall's agorithm.*/
#include<stdio.h>
void warshall(int[10][10],int);
void main()
{
int a[10][10],i,j,n;
clrscr();
printf("Enter the number of
nodes:"); scanf("%d",&n);
printf("\nEnter the adjacency
matrix:\n"); for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("The adjacency matirx
is:\n"); for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
warshall(a,n);
getch();
}
void warshall(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(j=1;j<=n;j++)
{
for(i=1;i<=n;i++)
{
if((p[i][j]==0) && (p[i][k]==1) && (p[k][j]==1))
{
p[i][j]=1;
}
}
}
}
printf("\nThe path matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",p[i][j]);
}
printf("\n");
}
}
OUTPUT:
Goal: Choose items with maximum total benefit but with weight at most W. i.e.
Objective: maximize
bi
iT
Constraint: wi W
iT
Algorithm: 0/1Knapsack(S, W)
//Input: set S of items with benefit bi and weight wi; max. weight
W //Output: benefit of best subset with weight at most W
// Sk: Set of items numbered 1 to k.
//Define B[k,w] = best selection from Sk with weight exactly equal to w
{
for w 0 to n-1 do
B[w] 0
for k 1 to n do
{
for w W downto wk do
{
if B[w-wk]+bk > B[w] then
B[w] B[w-wk]+bk
}
}
}
Complexity: The Time efficiency and Space efficiency of 0/1 Knapsack algorithm is (nW).
Program:
#include<stdio.h>
#define MAX 50
int p[MAX],w[MAX],n;
int knapsack(int,int);
int max(int,int);
void main()
{
int m,i,optsoln;
clrscr();
printf("\nEnter the
profits:\n"); for(i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("\nEnter the knapsack
capacity:"); scanf("%d",&m);
optsoln=knapsack(1,m);
printf("\nThe optimal soluntion
is:%d",optsoln); getch();
}
int knapsack(int i,int m)
{
if(i==n)
return (w[n]>m) ? 0 : p[n];
if(w[i]>m)
return knapsack(i+1,m);
return max(knapsack(i+1,m),knapsack(i+1,m-w[i])+p[i]);
}
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
OUTPUT:
Complexity: The Time efficiency for graphs represented by their weight matrix and the
priority queue implemented as an unordered array and for graphs represented by their
adjacency lists and the priority queue implemented as a min-heap, it is O(|E| log |V|).
Program:
/*To find shortest paths to other vertices using Dijkstra's algorithm.*/
#include<stdio.h>
void dij(int,int [20][20],int [20],int [20],int);
void main()
{
int i,j,n,visited[20],source,cost[20][20],d[20];
clrscr();
{
if(d[i]<min)
{
min=d[i];
u=i;
}
}
} //for i
visited[u]=1;
for(w=1;w<=n;w++)
{
if(cost[u][w]!=999 && visited[w]==0)
{
if(d[w]>cost[u][w]+d[u])
d[w]=cost[u][w]+d[u];
}
} //for w
} // for j
}
OUTPUT:
Algorithm : Kruskal(G)
// Kruskals algorithm for constructing a minimum spanning
tree //Input: A weighted connected graph G=(V,E)
//Output: ET,the set of edges composing a minimum spanning tree of G
{
Sort E in non decreasing order of the edge weights w(ei1)<=.>= w(ei
|E|)) ET ; ecounter 0 //Initialize the set of tree edges and its size
k 0 //initialize the number of processed
edges while ecounter <|V|-1 do
{
k
k+1
if ETU {eik} is acyclic
ET ET U {eik}; ecounter ecounter+1
}
return ET
}
Complexity: With an efficient sorting algorithm, the time efficiency of kruskals algorithm will
be in O(|E| log |E|).
Program:
#include<stdio.h> int
ne=1,min_cost=0;
void main()
{
int n,i,j,min,a,u,b,v,cost[20][20],parent[20];
clrscr();
scanf("%d",&cost[i][j]);
for(i=1;i<=n;i++)
parent[i]=0;
printf("\nThe edges of spanning tree
are\n"); while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(parent[u])
u=parent[u];
while(parent[v])
v=parent[v];
if(u!=v)
{
printf("Edge %d\t(%d->%d)=%d\n",ne++,a,b,min);
min_cost=min_cost+min;
parent[v]=u;
}
cost[a][b]=cost[a][b]=999;
}
printf("\nMinimum
cost=%d\n",min_cost); getch();
}
OUTPUT:
Algorithm : BFS(G)
//Implements a breadth-first search traversal of a given
graph //Input: Graph G = (V, E)
//Output: Graph G with its vertices marked with consecutive integers in the
order they //have been visited by the BFS traversal
{
mark each vertex with 0 as a mark of being
unvisited count 0
for each vertex v in V do
{
if v is marked with
0 bfs(v)
}
}
Algorithm : bfs(v)
//visits all the unvisited vertices connected to vertex v and assigns them the
numbers //in order they are visited via global variable count
{
count count + 1
mark v with count and initialize queue
with v while queue is not empty do
{
a := front of queue
for each vertex w adjacent to a do
{
if w is marked with 0
{
count count + 1
mark w with count
Complexity:
BFS has the same efficiency as DFS: it is (V2) for Adjacency matrix representation and
(V+E) for Adjacency linked list representation.
Program:
/*Print all the nodes reachable from a given starting node in a digraph using BFS method.*/
#include<stdio.h>
void BFS(int [20][20],int,int [20],int);
void main()
{
int n,a[20][20],i,j,visited[20],source;
clrscr();
while(f<=r)
{
u=queue[f++];
for(v=1;v<=n;v++)
{
if(a[u][v]==1 && visited[v]==0)
{
queue[++r]=v;
visited[v]=1;
}
} //for v
} // while
}
OUTPUT:
{
count count+1
mark v with count
Complexity: For the adjacency matrix representation, the traversal time efficiency is in
2
(|V| ) and for the adjacency linked list representation, it is in (|V|+|E|), where |V| and |E|
are the number of graphs vertices and edges respectively.
Program:
/* Check whether a given graph is connected or not using DFS method.*/
#include<stdio.h>
void DFS(int [20][20],int,int [20],int);
void main()
{
int n,a[20][20],i,j,visited[20],source;
clrscr();
OUTPUT:
j=k
{
x[k] 1 //generate left
child if (s+w[k] = m)
write (x[1...n]) //subset found
else if ( s + w[k]+w[k+1] <= m)
Complexity:
Subset sum problem solved using backtracking generates at each step maximal two new
n
subtrees, and the running time of the bounding functions is linear, so the running time is O(2 ).
Program:
/* Find a subset of a given set S={s1,s2...sn} of n positive integers whose sum is eqal
to a given positive integer d.A suitable message is to be displayed if the given
problem instance doesn't have a solution.*/
#include<stdio.h>
void subset(int,int,int); int
x[10],w[10],d,count=0;
void main()
{
int i,n,sum=0;
clrscr();
{
printf("\n\nSubset
%d\n",++count); for(i=0;i<=k;i++)
if(x[i]==1)
printf("%d\t",w[i]);
}
else
if(cs+w[k]+w[k+1]<=d)
subset(cs+w[k],k+1,r-w[k]);
}
}
OUTPUT:
Program:
#include<stdio.h>
int s,c[100][100],ver;
float optimum=999,sum;
}
}
else
// recursively explore the permutations starting at index i going through
index n-1*/ for (j=i; j<n; j++)
{ /* try the array with i and j switched
*/ swap (v, i, j);
brute_force (v, n, i+1);
/* swap them back the way they
were */ swap (v, i, j);
}
}
void nearest_neighbour(int ver)
{
int min,p,i,j,vis[20],from;
for(i=1;i<=ver;i++)
vis[i]=0;
vis[s]=1;
from=s;
sum=0;
for(j=1;j<ver;j++)
{
min=999;
for(i=1;i<=ver;i++)
if(vis[i] !=1 &&c[from][i]<min && c[from][i] !=0 )
{
min= c[from][i];
p=i;
}
vis[p]=1;
from=p;
sum=sum+min;
}
sum=sum+c[from][s];
}
void main ()
{
int ver,v[100],i,j;
clrscr();
printf("Enter n : ");
scanf("%d",&ver);
for (i=0; i<ver; i++)
v[i] = i+1;
printf("Enter cost matrix\n");
for(i=1;i<=ver;i++)
for(j=1;j<=ver;j++)
scanf("%d",&c[i][j]);
printf("\nEnter source :
"); scanf("%d",&s);
brute_force (v, ver, 0);
printf("\nOptimum solution with brute force technique is=%f\n",optimum);
nearest_neighbour(ver);
printf("\nSolution with nearest neighbour technique is=%f\n",sum);
printf("The approximation val is=%f",((sum/optimum)1)*100); printf(" % ");
getch();
}
10.
Find Minimum Cost Spanning Tree of a
given undirected graph using Prims algorithm.
Prims Algorithm:
Prims algorithm finds the minimum spanning tree for a weighted connected graph G=(V,E) to
get an acyclic subgraph with |V|-1 edges for which the sum of edge weights is the smallest.
Consequently the algorithm constructs the minimum spanning tree as expanding sub-trees. The
initial subtree in such a sequence consists of a single vertex selected arbitrarily from the set V of
the graphs vertices. On each iteration, we expand the current tree in the greedy manner by
simply attaching to it the nearest vertex not in that tree. The algorithm stops after all the graphs
vertices have been included in the tree being constructed.
Algorithm : Prim(G)
// Prims algorithm for constructing a minimum spanning
tree //Input: A weighted connected graph G=(V,E)
//Output: ET,the set of edges composing a minimum spanning tree of G
{
VT {v0} //the set of tree vertices can be initialized with any
vertex ET
for i 0 to |V| - 1 do
find a minimum-weight edge e* = (v*, u*) among all the edges
(v, u) such that v is in VT and u is in V-VT
VT VT U {u*}
ET ET U {e*}
return ET
}
Complexity: The time efficiency of prims algorithm will be in O(|E| log |V|).
Program:
#include<stdio.h>
int ne=1,min_cost=0;
void main()
{
int n,i,j,min,cost[20][20],a,u,b,v,source,visited[20];
clrscr();
printf("\nEdge %d\t(%d->%d)=%d\n",ne++,a,b,min);
min_cost=min_cost+min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum
cost=%d\n",min_cost); getch();
}
OUTPUT:
11.
Implement All-Pairs Shortest Paths Problem
using Floyd's algorithm. Parallelize this
algorithm, implement it using OpenMP and
determine the speed-up achieved.
Floyds Algorithm:
Floyds algorithm is applicable to both directed and undirected graphs provided that they do not
contain a cycle. It is convenient to record the lengths of shortest path in an n- by- n matrix D called the
distance matrix. The element dij in the ith row and jth column of matrix indicates the shortest path from
the ith vertex to jth vertex (1<=i, j<=n). The element in the ith row and jth column of the current matrix
(k-1)
D
is replaced by the sum of elements in the same row i and kth column and in the same column j
and the kth column if and only if the latter sum is smaller than its current value.
Algorithm Floyd(W[1..n,1..n])
//Implements Floyds algorithm for the all-pairs shortest paths
problem //Input: The weight matrix W of a graph
//Output: The distance matrix of shortest paths length
{
DW
for k1 to n do
{
for i 1 to n do
{
for j 1 to n do
{
D[i,j] min (D[i, j], D[i, k]+D[k, j] )
}
}
}
return D
}
3
Program:
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
#include<omp.h>
#include<conio.h>
void floyd(int[10][10],int);
int min(int,int);
void main()
{
int n,a[10][10],i,j;
printf("Enter the no.of nodes :
"); scanf("%d",&n);
printf("\nEnter the cost adjacency
matrix\n"); for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
floyd(a,n);
getch();
}
void floyd(int a[10][10],int n)
{
int d[10][10],i,j,k;
#pragma omp parallel for
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
d[i][j]=a[i][j];
}
#pragma omp parallel for
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
int min (int a,int b)
{
if(a<b)
return a;
else
return b;
}
OUTPUT:
Program:
/* Implement N Queen's problem using Back Tracking.*/
#include<stdio.h>
void nqueens(int);
int place(int[],int);
void printsolution(int,int[]);
void main()
{
int n;
clrscr();
while(k!=0)
{
x[k]=x[k]+1;
while(x[k]<=n&&(!place(x,k)))
x[k]=x[k]+1;
if(x[k]<=n)
{
if(k==n)
{
count++;
printf("\nSolution %d\n",count);
printsolution(n,x);
}
else
{
k++;
x[k]=0;
}
}
else
{
k--; //backtracking
}
}
return;
}
OUTPUT: