Algorithm Laboratory
1. 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>
#include <stdlib.h>
int i, j, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9] = {0};
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;
}
void main() {
printf("\nEnter the number 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;
}
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
}
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("\nMinimum cost = %d\n", mincost);
}
Output:
Enter the no. of vertices:4
Enter the cost adjacency matrix:
0 5 1 8
5 0 0 2
1 0 0 3
8 2 3 0
The edges of Minimum Cost Spanning Tree are
1 edge (1,3) =1
2 edge (2,4) =2
3 edge (3,4) =3
Minimum cost = 6
JSSATEB Dept. of Information Science
Algorithm Laboratory
2. 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>
int visited[10] = {0}, cost[10][10], min, mincost = 0;
int prims(int num) {
int i, j, ne = 1, a, b;
visited[1] = 1;
while (ne < num) {
for (i = 1, min = 999; i <= num; i++) {
for (j = 1; j <= num; j++) {
if (cost[i][j] < min && visited[i] != 0 && visited[j] == 0) {
min = cost[i][j];
a = i;
b = j;
}
}
}
printf("\nEdge %d: (%d - %d) cost: %d", ne++, a, b, min);
mincost += min;
visited[b] = 1;
cost[a][b] = cost[b][a] = 999;
}
printf("\n\nMinimum cost = %d\n", mincost);
}
void main() {
int num, i, j;
printf("\nEnter the number of nodes: ");
scanf("%d", &num);
printf("\nEnter the adjacency matrix:\n");
for (i = 1; i <= num; i++) {
for (j = 1; j <= num; j++) {
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0) {
cost[i][j] = 999;
}
}
}
prims(num);
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
Output:
Enter the number of nodes= 4
Enter the adjacency matrix
0 5 1 8
5 0 0 2
1 0 0 3
8 2 3 0
Edge 1:(1 - 3) cost:1
Edge 2:(3 - 4) cost:3
Edge 3:(4 - 2) cost:2
Minimum cost = 6
JSSATEB Dept. of Information Science
Algorithm Laboratory
3A. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd’s algorithm.
#include <stdio.h>
int min(int a, int b) {
return (a < b) ? a : b;
}
void floyd(int p[10][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;
printf("\nEnter the number of vertices: ");
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]);
floyd(a, n);
printf("\nShortest Path Matrix:\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
Output:
Enter the n value:4
JSSATEB Dept. of Information Science
Algorithm Laboratory
Enter the graph data:
0 8 999 1
999 0 999 2
5 999 0 999
999 999 3 0
Shortest path matrix
0 8 4 1
10 0 5 2
5 13 0 6
8 16 3 0
JSSATEB Dept. of Information Science
Algorithm Laboratory
3B. Design and implement C/C++ Program to find the transitive closure using Warshal’s
algorithm.
#include<stdio.h>
#include <stdio.h>
void warsh(int p[10][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]);
}
void main() {
int a[10][10], n, i, j;
printf("\nEnter the number of vertices: ");
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]);
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");
}
}
Output:
Enter the n value:4
Enter the graph data:
0111
1001
1001
1110
JSSATEB Dept. of Information Science
Algorithm Laboratory
Resultant path matrix
1111
1111
1111
1111
JSSATEB Dept. of Information Science
Algorithm Laboratory
4. Design and implement C/C++ Program to find shortest paths from a given vertex in a
weighted connected graph to other vertices using Dijkstra’s algorithm.
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define MAX_VERTICES 10
#define INF INT_MAX
int minDistance(int dist[], bool sptSet[], int V) {
int min = INF, min_index;
for (int i = 0; i < V; i++) {
if (sptSet[i] == false && dist[i] <= min) {
min = dist[i];
min_index = i;
}
}
return min_index;
}
void printSolution(int dist[], int V) {
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int src, int V) {
int dist[MAX_VERTICES];
bool sptSet[MAX_VERTICES];
for (int i = 0; i < V; i++) {
dist[i] = INF;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet, V);
sptSet[u] = true;
for (int i = 0; i < V; i++) {
if (!sptSet[i] && graph[u][i] &&
dist[u] != INF && dist[u] + graph[u][i] < dist[i]) {
dist[i] = dist[u] + graph[u][i];
}
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
}
printSolution(dist, V);
}
void main() {
int V, E;
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
int graph[MAX_VERTICES][MAX_VERTICES] = {{0}};
printf("Enter the source vertex, destination vertex, and weight for each edge:\n");
for (int i = 0; i < E; i++) {
int source, dest, weight;
scanf("%d%d%d", &source, &dest, &weight);
graph[source][dest] = weight;
}
dijkstra(graph, 0, V);
}
Output:
Enter the number of vertices: 4
Enter the number of edges: 5
Enter the source vertex, destination vertex, and weight for each edge:
0 1 8
0 3 1
1 3 2
2 0 5
3 2 3
Vertex Distance from Source
0 0
1 8
2 4
3 1
JSSATEB Dept. of Information Science
Algorithm Laboratory
5. Design and implement C/C++ Program to obtain the Topological ordering of vertices in
a given digraph.
#include <stdio.h>
int adj[10][10], n, colsum[10];
void calcolsum() {
for (int j = 0; j < n; j++) {
colsum[j] = 0;
for (int i = 0; i < n; i++)
colsum[j] += adj[i][j];
}
}
void source_removal() {
int i, j, k, select[10] = {0};
printf("Topological ordering is: ");
for (i = 0; i < n; i++) {
calcolsum();
for (j = 0; j < n; j++) {
if (select[j] == 0 && colsum[j] == 0)
break;
}
printf("%d ", j + 1);
select[j] = 1;
for (k = 0; k < n; k++)
adj[j][k] = 0;
}
}
void main() {
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &adj[i][j]);
source_removal();
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
Output:
enter the no of vertices 4
enter the adjacency matrix
0111
0001
0000
0010
topological ordering is 1 2 4 3
JSSATEB Dept. of Information Science
Algorithm Laboratory
6. 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 K[W + 1];
for (int w = 0; w <= W; w++) {
K[w] = 0;
}
for (int i = 0; i < n; i++) {
for (int w = W; w >= wt[i]; w--) {
K[w] = max(K[w], val[i] + K[w - wt[i]]);
}
}
return K[W];
}
void main() {
int val[100], wt[100];
int W, n;
printf("Enter the number of items: ");
scanf("%d", &n);
printf("Enter the values and weights of %d items:\n", n);
for (int i = 0; i < n; i++) {
printf("Item %d - Weight and Value: ", i + 1);
scanf("%d %d", &wt[i], &val[i]);
}
printf("Enter the knapsack capacity: ");
scanf("%d", &W);
printf("Maximum value that can be obtained: %d\n", knapsack(W, wt, val, n));
}
Output:
Enter the number of items: 3
Enter the values and weights of 3 items:
Item 1 - Weight and Value : 1 15
Item 2 - Weight and Value : 2 40
Item 3 - Weight and Value : 3 15
Enter the knapsack capacity: 4
Maximum value that can be obtained: 55
JSSATEB Dept. of Information Science
Algorithm Laboratory
7. Design and implement C/C++ Program to solve discrete Knapsack and continuous
Knapsack problems using greedy approximation methods.
#include <stdio.h>
void main() {
float weight[50], profit[50], ratio[50], Totalvalue = 0, temp;
float capacity, amount;
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:\n");
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("Knapsack problem using Greedy Algorithm:\n");
for (i = 0; i < n; i++) {
if (weight[i] > capacity)
break;
else {
JSSATEB Dept. of Information Science
Algorithm Laboratory
Totalvalue += profit[i];
capacity -= weight[i];
}
}
if (i < n)
Totalvalue += (ratio[i] * capacity);
printf("\nThe maximum value is: %.2f\n", Totalvalue);
}
Output:
Enter the number of items :3
Enter Weight and Profit for item[1] :
1 15
Enter Weight and Profit for item[2] :
2 40
Enter Weight and Profit for item[3] :
3 15
Enter the capacity of knapsack :
4
Knapsack problems using Greedy Algorithm:
The maximum value is :60.000000
JSSATEB Dept. of Information Science
Algorithm Laboratory
8. Design and implement C/C++ Program to find a subset of a given set S = {s1 , s2,…..,sn}
of n positive integers whose sum is equal to a given positive integer d.
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
void subsetSum(int set[], int subset[], int n, int subSize, int total, int nodeCount, int sum) {
if (total == sum) {
printf("Subset found: { ");
for (int i = 0; i < subSize; i++)
printf("%d ", subset[i]);
printf("}\n");
return;
} else {
for (int i = nodeCount; i < n; i++) {
subset[subSize] = set[i];
subsetSum(set, subset, n, subSize + 1, total + set[i], i + 1, sum);
}
}
}
void main() {
int set[MAX_SIZE];
int subset[MAX_SIZE];
int n, sum;
printf("Enter the number of elements in the set: ");
scanf("%d", &n);
printf("Enter the elements of the set:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &set[i]);
}
printf("Enter the sum to find subset for: ");
scanf("%d", &sum);
printf("Subsets with sum %d:\n", sum);
subsetSum(set, subset, n, 0, 0, 0, sum);
}
Output:
Enter the number of elements in the set: 5
Enter the elements of the set:
12345
Enter the sum to find subset for: 5
Subsets with sum 5:
Subset found: { 1 4 }
Subset found: { 2 3 }
Subset found: { 5 }
JSSATEB Dept. of Information Science
Algorithm Laboratory
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;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void generateRandomNumbers(int arr[], int n) {
for (int i = 0; i < n; i++) {
arr[i] = rand() % 10000;
}
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
if (n <= 5000) {
printf("Please enter a value greater than 5000\n");
return 0;
}
int *arr = (int *)malloc(n * sizeof(int));
generateRandomNumbers(arr, n);
clock_t start = clock();
selectionSort(arr, n);
clock_t end = clock();
JSSATEB Dept. of Information Science
Algorithm Laboratory
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Sorted array \n");
for (int i = 0; i < 20; i++)
printf("%d\n", arr[i]);
printf("\nTime taken to sort %d elements: %f seconds\n", n, time_taken);
free(arr);
}
Output:
Enter number of elements: 300
Please enter a value greater than 5000
------------------------------------
Enter number of elements: 5001
sorted array
0 1 3 5 8 10 12 12 12 14 17 19 19 27 28 29 30 30 32 34
Time taken to sort 5001 elements: 0.018062 seconds
JSSATEB Dept. of Information Science
Algorithm Laboratory
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.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int partition(int arr[], int left, int right) {
int i = left + 1;
int j = right;
int temp, pivot = arr[left];
while (i <= j) {
while (i <= right && arr[i] <= pivot)
i++;
while (j >= left + 1 && arr[j] > pivot)
j--;
if (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[left];
arr[left] = arr[j];
arr[j] = temp;
return j;
}
void quickSort(int arr[], int left, int right) {
if (left < right) {
int pi = partition(arr, left, right);
quickSort(arr, left, pi - 1);
quickSort(arr, pi + 1, right);
}
}
void generateRandomNumbers(int arr[], int n) {
for (int i = 0; i < n; i++)
arr[i] = rand() % 100000;
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
if (n <= 5000) {
printf("Please enter a value greater than 5000\n");
return 0;
}
int *arr = (int *)malloc(n * sizeof(int));
generateRandomNumbers(arr, n);
clock_t start = clock();
quickSort(arr, 0, n - 1);
clock_t end = clock();
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Sorted array :\n");
for (int i = 0; i < 20 ; i++)
printf("%d\n", arr[i]);
printf("\nTime taken to sort %d elements: %f seconds\n", n, time_taken);
free(arr);
}
Output:
Enter number of elements: 600
Please enter a value greater than 5000
-----------------------------------
Enter number of elements: 5001
sorted array
10 30 34 77 81 93 96 113 117 131 202 237 255 272 305 313 323 335 346 361
Time taken to sort 5001 elements: 0.000567 seconds
JSSATEB Dept. of Information Science
Algorithm Laboratory
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.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void merge(int arr[], int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
int b[right + 1];
while (i <= mid && j <= right) {
if (arr[i] <= arr[j])
b[k++] = arr[i++];
else
b[k++] = arr[j++];
}
while (i <= mid)
b[k++] = arr[i++];
while (j <= right)
b[k++] = arr[j++];
for (int i = left; i <= right; i++)
arr[i] = b[i];
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
void generateRandomArray(int arr[], int n) {
for (int i = 0; i < n; i++)
arr[i] = rand() % 100000;
}
int main() {
int n;
JSSATEB Dept. of Information Science
Algorithm Laboratory
printf("Enter the number of elements: ");
scanf("%d", &n);
if (n <= 5000) {
printf("Please enter a value greater than 5000\n");
return 0;
}
int *arr = (int *)malloc(n * sizeof(int));
generateRandomArray(arr, n);
clock_t start = clock();
mergeSort(arr, 0, n - 1);
clock_t end = clock();
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Sorted array :\n");
for (int i = 0; i < 20 ; i++)
printf("%d\n", arr[i]);
printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);
free(arr);
}
Output:
Enter the number of elements: 800
Please enter a value greater than 5000
-------------------------------------------
Enter the number of elements: 5001
Time taken to sort 5001 elements: 0.000729 seconds
sorted array
10 30 34 77 81 93 96 113 117 131 202 237 255 272 305 313 323 335 346 361
Time taken to sort 5001 elements: 0.000729 seconds
JSSATEB Dept. of Information Science
Algorithm Laboratory
12. Design and implement C/C++ Program for N Queen’s problem using Backtracking.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int board[20], count;
void print(int n) {
int i, j;
printf("\n\nSolution %d:\n\n", ++count);
for (i = 1; i <= n; ++i)
printf("\t%d", i);
for (i = 1; i <= n; ++i) {
printf("\n\n%d", i);
for (j = 1; j <= n; ++j) {
if (board[i] == j)
printf("\tQ");
else
printf("\t-");
}
}
}
int place(int row, int column) {
int i;
for (i = 1; i <= row - 1; ++i) {
if (board[i] == column)
return 0;
if (abs(board[i] - column) == abs(i - row))
return 0;
}
return 1;
}
void queen(int row, int n) {
int column;
for (column = 1; column <= n; ++column) {
if (place(row, column)) {
board[row] = column;
if (row == n)
print(n);
else
queen(row + 1, n);
}
}
JSSATEB Dept. of Information Science
Algorithm Laboratory
}
void main() {
int n;
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens: ");
scanf("%d", &n);
queen(1, n);
if (count == 0)
printf("\n\nNo solution is possible for %d queens.\n", n);
}
Output:
- N Queens Problem Using Backtracking -
Enter number of Queens:4
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - - -
4 - - Q -
Solution 2:
1 2 3 4
1 - - Q -
2 Q - - -
3 - - - Q
4 - Q - -
--------------------------------------------------
Enter number of Queens:3
No solution is possible for 3 queens.
JSSATEB Dept. of Information Science