Kruskal's algorithm
Design and implement C/C++ Program to find Minimum Cost
Spanning Tree of a given connected undirected graph using
Kruskal's algorithm.
#include <stdio.h>
int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[10][10], parent[10]; int find(int);
int uni(int, int); void
main() {
printf("\n\tImplementation of Kruskal's Algorithm\n"); printf("\nEnter the no. of
vertices:");
scanf("%d", & n);
printf("\nEnter the cost adjacency matrix:\n"); for (i = 1; i <= n;
i++) {
for (j = 1; j <= n; j++) { scanf("%d",
& cost[i][j]); if (cost[i][j] == 0)
cost[i][j] = 999;
}
}
printf("The edges of Minimum Cost Spanning Tree are\n"); while (ne < n) {
for (i = 1, min = 999; i <= n; i++) {
for (j = 1; j <= n; j++) { if
(cost[i][j] < min) {
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}
u = find(u); v =
find(v);
if (uni(u, v)) {
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min); mincost += min;
cost[a][b] = cost[b][a] = 999;
}
printf("\n\tMinimum cost = %d\n", mincost);
}
int find(int i) { while
(parent[i]) i =
parent[i]; return i;
}
int uni(int i, int j) { if (i !=
j) { parent[j] = i; return
1;
}
return 0;
}
OUTPUT:
Implementation of Kruskal's Algorithm Enter the no. of
vertices: 6
Enter the cost adjacency matrix:
0 3 10 10 6 5
3 0 1 10 10 4
10 1 0 6 10 4
10 10 6 0 8 5
6 10 10 8 0 2
544520
The edges of Minimum Cost Spanning Tree are
1 edge (2,3) =1
2 edge (5,6) =2
3 edge (1,2) =3
4 edge (2,6) =4
5 edge (4,6) =5
Minimum cost = 15
Prim's algorithm
Design and implement C/C++ Program to find Minimum Cost Spanning Tree
of a given connected undirected graph using Prim's algorithm.
#include <stdio.h>
#include <limits.h>
#define MAX 20
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[], int vertices)
{
int min = INT_MAX, minIndex;
for (int v = 0; v < vertices; v++)
{
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
// Function to print the constructed MST stored in parent[]
void printMST(int parent[], int graph[MAX][MAX], int vertices)
{
printf("Edge \tWeight\n");
for (int i = 1; i < vertices; i++)
{
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
}
}
// Function to implement Prim's algorithm for a given graph
void primMST(int graph[MAX][MAX], int vertices)
{
int parent[MAX]; // Array to store the constructed MST
int key[MAX]; // Key values used to pick the minimum weight edge
int mstSet[MAX]; // To represent set of vertices included in MST
// Initialize all keys as INFINITE and mstSet[] as false
for (int i = 0; i < vertices; i++)
{
key[i] = INT_MAX;
mstSet[i] = 0;
}
// Always include the first vertex in the MST
key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always the root of the MST
// The MST will have vertices-1 edges
for (int count = 0; count < vertices - 1; count++)
{
// Pick the minimum key vertex from the set of vertices not yet included in the MST
int u = minKey(key, mstSet, vertices);
// Add the picked vertex to the MST Set
mstSet[u] = 1;
// Update key value and parent index of the adjacent vertices
for (int v = 0; v < vertices; v++)
{
// graph[u][v] is non-zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if the graph[u][v] is smaller than the key[v]
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Print the constructed MST
printMST(parent, graph, vertices);
}
int main()
{
int vertices;
// Input the number of vertices
printf("Input the number of vertices: ");
scanf("%d", &vertices);
int graph[MAX][MAX];
// Input the adjacency matrix representing the graph
printf("Input the adjacency matrix for the graph:\n");
for (int i = 0; i < vertices; i++)
{
for (int j = 0; j < vertices; j++)
{
scanf("%d", &graph[i][j]);
}
}
// Perform Prim's algorithm to find the MST
primMST(graph, vertices);
return 0;
}
Output:
Input the number of vertices: 5
Input the adjacency matrix for the graph:
02060
20385
03007
68009
05790
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Warshal’s Program
Design and implement C/C++ Program to find the transitive closure using
Warshal's algorithm.
# include <stdio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1)
p[i][j]=1;
}
void main()
{
int i,j;
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is shown below\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
}
OUTPUT
Enter the number of nodes:4
Enter the adjacency matrix:
0100
0001
0000
1010
The path matrix is shown below
1111
1111
0000
1111
Floyd's Program
Design and implement C/C++ Program to solve All-Pairs Shortest Paths
problem using Floyd's algorithm.
#include <stdio.h>
// defining the number of vertices
#define nV 4
#define INF 999
void printMatrix(int matrix[][nV]);
// Implementing floyd warshall algorithm
void floydWarshall(int graph[][nV])
int matrix[nV][nV], i, j, k;
for (i = 0; i < nV; i++)
for (j = 0; j < nV; j++)
matrix[i][j] = graph[i][j];
// Adding vertices individually
for (k = 0; k < nV; k++)
for (i = 0; i < nV; i++)
for (j = 0; j < nV; j++)
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
printMatrix(matrix);
void printMatrix(int matrix[][nV])
printf("All pairs shortest path is\n");
for (int i = 0; i < nV; i++)
for (int j = 0; j < nV; j++)
if (matrix[i][j] == INF)
printf("%4s", "INF");
else
printf("%4d", matrix[i][j]);
printf("\n");
int main() {
int graph[nV][nV] = {{INF, 1,4,6},
{INF, INF,7, 4},
{2,INF, INF,3},
{INF, INF, INF, INF}};
floydWarshall(graph);
Output
1)
All pairs shortest path is
6 1 4 5
9 10 7 4
2 3 6 3
INF INF INF INF
2)
int main()
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}};
floydWarshall(graph);
All pairs shortest path is
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0
3)
int main()
int graph[nV][nV] = {{0,INF,3,INF},
{2, 0, INF, INF},
{INF, 7, 0, 1},
{6, INF, INF, 0}};
floydWarshall(graph);
All pairs shortest path is
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
Dijkstra's algorithm
Design and implement C/C++ Program to find shortest paths from a given
vertex in a weighted connected graph to other V using Dijkstra's algorithm
#include <stdio.h>
#include <limits.h>
#define MAX 50
int minDistance(int dist[], int sptSet[], int V)
{
int min = INT_MAX, minIndex;
for (int v = 0; v < V; v++)
{
if (!sptSet[v] && dist[v] < min)
{
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
void printSolution(int dist[], int V)
{
printf("Vertex \tDistance from Source\n");
for (int i = 0; i < V; i++)
{
printf("%d \t%d\n", i, dist[i]);
}
}
void dijkstra(int graph[MAX][MAX], int src, int V)
{
int dist[MAX];
int sptSet[MAX];
for (int i = 0; i < V; i++)
{
dist[i] = INT_MAX;
sptSet[i] = 0;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet, V);
sptSet[u] = 1;
for (int v = 0; v < V; v++)
{
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] <
dist[v])
{
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist, V);
}
int main() {
int V;
printf("Input the number of vertices: ");
scanf("%d", &V);
int graph[MAX][MAX];
printf("Input the adjacency matrix for the graph:\n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
scanf("%d", &graph[i][j]);
}
}
int source;
printf("Input the source vertex: ");
scanf("%d", &source);
dijkstra(graph, source, V);
return 0;
}
Output:
1) Input the number of vertices: 5
Input the adjacency matrix for the graph:
03200
30010
20014
01102
00420
Input the source vertex: 0
Vertex Distance from Source
0 0
1 3
2 2
3 3
4 5
2) Input the number of vertices: 7
Input the adjacency matrix for the graph:
0400080
4 0 8 0 0 11 0
0807040
0 0 7 0 9 14 0
0 0 0 9 0 10 2
0 0 4 14 10 0 2
0000201
Input the source vertex: 0
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 12
5 8
6 10
Topological ordering
Design and implement C/C++ Program to obtain the Topological ordering of
vertices in a Given digraph.
#include<stdio.h>
const int MAX = 10;
void fnTopological(int a[MAX][MAX], int n);
int main(void)
int a[MAX][MAX],n;
int i,j;
printf("Topological Sorting Algorithm -\n");
printf("\nEnter the number of vertices : ");
scanf("%d",&n);
printf("Enter the adjacency matrix -\n");
for (i=0; i<n; i++)
for (j=0; j<n; j++)
scanf("%d",&a[i][j]);
fnTopological(a,n); printf("\n");
return 0;
void fnTopological(int a[MAX][MAX], int n)
int in[MAX], out[MAX], stack[MAX], top=-1; int i,j,k=0;
for (i=0;i<n;i++)
in[i] = 0;
for (j=0; j<n; j++)
if (a[j][i] == 1)
in[i]++;
while(1)
for (i=0;i<n;i++)
if (in[i] == 0)
stack[++top] = i;
in[i] = -1;
if (top == -1) break;
out[k] = stack[top--];
for (i=0;i<n;i++)
if (a[out[k]][i] == 1)
in[i]--;
k++;
}
printf("Topological Sorting (JOB SEQUENCE) is:- \n");
for (i=0;i<k;i++)
printf("%d ",out[i] + 1);
OUTPUT:
Topological Sorting Algorithm -
Enter the number of vertices: 5
Enter the adjacency matrix -
00100
00100
00011
00001
00000
Topological Sorting (JOB SEQUENCE) is:-
21345
11. Design and implement C/C++ Program to obtain the Topological ordering
of vertices in a Given digraph.
#include<stdio.h>
#include<stdlib.h>
int a[10][10],n,indegree[10];
void find_degree()
int i,j,sum;
for(j=0;j<n;j++)
sum=0;
for(i=0;i<n;i++)
sum=sum+a[i][j];
indegree[j]=sum;
void topology()
int i,u,v,t[10],s[10],top=-1,k=0;
find_degree();
for(i=0;i<n;i++)
if(indegree[i]==0)
s[++top]=i;
while(top!=-1)
{
u=s[top--];
t[k++]=u;
for(v=0;v<n;v++)
if(a[u][v]==1)
indegree[v]--;
if(indegree[v]==0)
s[++top]=v;
printf("\n topological ordering;\n");
for(i=0;i<n;i++)
printf("%d\t",t[i]);
void main()
int i,j;
printf("enter the no of nodes:");
scanf("%d",&n);
printf("enter the adjacency matrix\n:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
topology();
}
Design and implement C/C++ Program to solve 0/1 Knapsack
problem using Dynamic Programming method.
#include<stdio.h> int
max(int a, int b)
{
return (a > b)? a : b;
int knapSack(int W, int wt[], int val[], int n)
int i, j;
int K[n+1][W+1];
for (i = 0; i <= n; i++)
for (j = 0; j <= W; j++)
if (i==0 || j==0) K[i][j] = 0;
else if (wt[i-1] <= j)
K[i][j] = max(val[i-1] + K[i-1][j-wt[i-1]], K[i-1][j]); else
K[i][j] = K[i-1][j];
return K[n][W];
int main()
int i, n, val[20], wt[20], W; printf("Enter number of
items:"); scanf("%d", &n);
printf("Enter value and weight of items:\n"); for(i = 0;i < n; i++)
{
scanf("%d%d", &val[i], &wt[i]);
printf("Enter size of knapsack:"); scanf("%d", &W);
printf("%d", knapSack(W, wt, val, n)); return 0;
}
0utput
Enter number of items: 3
Enter value and weight of items: 100 20
50 10
150 30
Enter size of knapsack: 50 250
Design and implement C/C++ Program to solve discrete Knapsack and
continuous Knapsack problems using greedy approximation method.
#include <stdio.h>
float Knapsack(float weight[], float profit[], float ratio[],
float capacity, int n, int isDiscrete)
{
int i;
float totalValue = 0;
if (isDiscrete)
{
for (i = 0; i < n; i++)
if (weight[i] <= capacity)
{
totalValue += profit[i];
capacity -= weight[i];
}
}
else
{
for (i = 0; i < n && weight[i] <= capacity; i++)
{
totalValue += profit[i];
capacity -= weight[i];
}
if (i < n)
totalValue += ratio[i] * capacity;
}
return totalValue;
}
int main()
{
float weight[50], profit[50], ratio[50], temp, capacity;
int n, i, j;
printf("Enter the number of items: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter Weight and Profit for item[%d]:\n", i + 1);
scanf("%f %f", &weight[i], &profit[i]);
}
printf("Enter the capacity of knapsack: ");
scanf("%f", &capacity);
for (i = 0; i < n; i++)
ratio[i] = profit[i] / weight[i];
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
printf("\nDiscrete Knapsack problems using Greedy Algorithm:\n");
printf("\tThe maximum value is[Discrete]: %f\n",
Knapsack(weight, profit, ratio, capacity, n, 1));
printf("\nContinuous Knapsack problems using Greedy Algorithm:\n");
printf("\tThe maximum value is[Continuous]: %f\n",
Knapsack(weight, profit, ratio, capacity, n, 0));
return 0;
}
OUTPUT:
Enter the number of items: 4
Enter Weight and Profit for item[1]:
7 42
Enter Weight and Profit for item[2]:
3 12
Enter Weight and Profit for item[3]:
4 40
Enter Weight and Profit for item[4]:
5 25
Enter the capacity of knapsack: 10
Discrete Knapsack problems using Greedy Algorithm:
The maximum value is[Discrete]: 65.000000
Continuous Knapsack problems using Greedy Algorithm:
The maximum value is[Continuous]: 76.000000
Subset program
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.
#include<stdio.h>
int subset(int,int);
int s[10],d,n,set[10],count=0;
void display(int);
int flag = 0;
void
main()
int i;
printf("ENTER THE NUMBER OF THE ELEMENTS IN THE SET : ");
scanf("%d",&n);
printf("ENTER THE SET OF VALUES : ");
for(i=0;i<n;i++)
scanf("%d",&s[i]);
printf("ENTER THE SUM :
");
scanf("%d",&d);
printf("THE PROGRAM OUTPUT IS: ");
subset(0,0);
if(flag == 0)
printf("There is no solution");
}
int subset(int sum,int i)
if(sum == d)
flag = 1;
display(count);
return 1;
if(sum>d || i>=n)return 1; else
set[count]=s[i];
count++;
subset(sum+s[i],i+1);
count--;
subset(sum,i+1);
void display(int count)
int i;
printf("\t{");
for(i=0;i<count;i++
printf("%d,",set[i]);
printf("}");
Output:
ENTER THE NUMBER OF THE ELEMENTS IN THE
SET : 5 ENTER THE SET OF VALUES : 6
ENTER THE SUM : 5
THE PROGRAM OUTPUT IS: {4,1,} {3,2,}
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> 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.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int n, i;
clock_t start, end;
double cpu_time_used;
printf("Enter the number of elements: ");
scanf("%d", &n);
int *arr = (int*)malloc(n * sizeof(int));
// Generating random numbers for array elements
srand(time(0));
for (i = 0; i < n; i++) {
arr[i] = rand() % 10000; // Generating numbers between 0 and 9999
}
// Sorting and calculating time taken
start = clock();
selectionSort(arr, n);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Sorted array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Time taken for sorting: %f seconds\n", cpu_time_used);
free(arr);
return 0;
}
Quick sort
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int partition(int a[],int low,int high)
{
int i,j,temp,pivot;
pivot=a[low];
i=low;
j=high+1;
while(i<=j)
{
do
i++;
while (pivot>=a[i]);
do
j--;
while(pivot<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
void qs (int a[],int low, int high)
{
int mid;
if(low<high)
{
mid=partition(a,low,high);
qs(a,low,mid-1);
qs(a,mid+1,high);
}
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Generate random numbers for the array
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000; // You can adjust the range of random numbers as needed
}
// Measure the time taken to sort the array
clock_t start, end;
double cpu_time_used;
start = clock();
qs(arr, 0, n - 1);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Time taken for sorting: %f seconds\n", cpu_time_used);
return 0;
}
Merge Sort
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Merge two subarrays of arr[]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int p = m - l + 1;
int q = r - m;
// Create temporary arrays
int L[p], R[q];
// Copy data to temporary arrays L[] and R[]
for (i = 0; i < p; i++)
L[i] = arr[l + i];
for (j = 0; j < q; j++)
R[j] = arr[m + 1 + j];
// Merge the temporary arrays back into arr[l..r]
i = 0;
j = 0;
k = l;
while (i < p && j < q)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < p)
{
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < q)
{
arr[k] = R[j];
j++;
k++;
}
}
// Merge sort function
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for large l and r
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Generate random numbers for the array
srand(time(NULL));
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 10000; // You can adjust the range of random numbers as needed
}
// Measure the time taken to sort the array
clock_t start, end;
double cpu_time_used;
start = clock();
mergeSort(arr, 0, n - 1);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Sorted array:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
printf("Time taken for sorting: %f seconds\n", cpu_time_used);
return 0;
}
N Queen's problem using Backtracking
Design and implement C/C++ Program for N Queen's problem using
Backtracking.
#include<stdio.h>
#include<math.h>
int x[10];
void main( )
int k, i, j, n, count=1;
int place(int);
printf("Enter the number of Queens\n");
scanf("%d",&n);
if(n==0 || n==2 || n==3 )
printf("No Solution");
else
k=1;
x[1]=0;
while(k)
x[k]= x[k]+1;
while( ( x[k] <=n) && (!place(k) ) )
x[k]= x[k]+1;
if( x[k]<=n )
{
if(k==n)
printf("Solution %d \n",count++);
for ( i=1; i<=n; i++ )
for ( j=1; j<x[i]; j++ )
printf(" * ");
printf(" Q" );
for ( j=x[i]+1; j<=n; j++ )
printf(" * ");
printf(" \n" );
else
k=k+1;
x[k]=0;
else
k=k-1;
}
int place( int p)
int i;
for ( i=1; i<=(p-1); i++ )
if((x[i]==x[p]) || ((abs(x[i]-x[p]))==(abs(i-p))))
return 0;
return 1;
OUTPUT: