0% found this document useful (0 votes)
26 views28 pages

ADA LAB MANUAL 2022 SCHEME (1)

The document outlines a series of C/C++ programming tasks focused on algorithm design and implementation for various problems, including Minimum Cost Spanning Trees using Kruskal's and Prim's algorithms, All-Pairs Shortest Paths using Floyd's algorithm, and Dijkstra's algorithm for shortest paths. It also covers the implementation of Topological sorting, the 0/1 Knapsack problem using Dynamic Programming, and both discrete and continuous Knapsack problems using greedy methods. Each section includes code snippets and explanations for the algorithms being implemented.

Uploaded by

suhasy756
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views28 pages

ADA LAB MANUAL 2022 SCHEME (1)

The document outlines a series of C/C++ programming tasks focused on algorithm design and implementation for various problems, including Minimum Cost Spanning Trees using Kruskal's and Prim's algorithms, All-Pairs Shortest Paths using Floyd's algorithm, and Dijkstra's algorithm for shortest paths. It also covers the implementation of Topological sorting, the 0/1 Knapsack problem using Dynamic Programming, and both discrete and continuous Knapsack problems using greedy methods. Each section includes code snippets and explanations for the algorithms being implemented.

Uploaded by

suhasy756
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Analysis & Design of Algorithms Lab 2023

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,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
printf("\n\n\tImplementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
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("\nThe edges of Minimum Cost Spanning Tree are\n\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))
{

1 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

printf("\n%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);
//getch();
}
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;
}

2 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the 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;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}

3 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

printf("\n Minimun cost=%d",mincost);


getch();
}

4 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

3a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths
problem using Floyd's algorithm.

#include<stdio.h>
#include<conio.h>
int min(int,int);
void floyds(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++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;
clrscr();
printf("\nEnter the number of vertices: ");
scanf("%d",&n);
printf("Enter the number of edges: ");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("Enter the end vertices of edge %d with its weight : ",i);
scanf("%d%d%d",&u,&v,&w);

5 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

p[u][v]=w;
}
printf("Matrix of input data\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\nTransitive closure \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
printf("\nThe shortest paths are \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n%d,%d>=%d",i,j,p[i][j]);
}
getch();
}

6 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

3b. Design and implement C/C++ Program to find the transitive closure using
Warshal'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]) {


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");
}

7 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

int main() {
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}};
floydWarshall(graph);
}

8 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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>
#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);

9 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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

10 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

5. Design and implement C/C++ Program to obtain the Topological ordering of


vertices in a given digraph.

#include <stdlib.h>
#include <stdio.h>

int **a, n, *visited, *res, *s, top = -1, k;

void dfs(int u)
{
int v;

s[++top] = u;
visited[u] = 1;

for (v = 0; v < n; v++) {


if (visited[v] != 1 && a[u][v] == 1) {
dfs(v);
}
}

res[k--] = s[top--];
}

void topological_sort()
{
int v;
for (v = 0; v < n; v++) {
if (visited[v] != 1) {
dfs(v);
}
}

printf("The topological ordering is : \n");


for (v = 0; v < n; v++) {
printf("%d\n", res[v]);
}

11 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

int main()
{
int i, j;

printf("Number of vertices : ");


scanf("%d", &n);

a = calloc(n, sizeof(int *));


for (i = 0; i < n; i++) {
a[i] = calloc(n, sizeof(int));
}
visited = calloc(n, sizeof(int));
res = calloc(n, sizeof(int));
s = calloc(n, sizeof(int));

printf("The elements : \n");


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}

k = n - 1;
topological_sort();
return 0;
}

12 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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

#include <stdlib.h>
#include <stdio.h>

int *p, *w, n, m, *sel;

int max(int a, int b)


{
return a > b ? a : b;
}

void knapsack()
{
int i, j, v[n+1][m+1];
for (i = 0; i <= n; i++)
{
for (j = 0; j <= m; j++)
{
if (i == 0 || j == 0)
{
v[i][j] = 0;
}
else if (j < w[i])
{
v[i][j] = v[i-1][j];
}
else
{
v[i][j] = max(v[i-1][j], p[i] + v[i-1][j-w[i]]);
}
}
}
printf("Maximum profit : %d\n", v[n][m]);
j = m;
for (i = n; i >= 0; i--)
{
if (v[i][j] != v[i-1][j])
{
sel[i] = 1;

13 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

j = j - w[i];
}
}

printf("The selected items are : \n");


for (i = 1; i <= n; i++) {
if (sel[i] == 1) {
printf("%d\t", i);
}
}
printf("\n");
}
int main()
{
int i;

printf("Number of items : ");


scanf("%d", &n);

printf("Knapsack capacity : ");


scanf("%d", &m);

p = calloc(n, sizeof(int));
w = calloc(n, sizeof(int));
sel = calloc(n, sizeof(int));

printf("Profit Array : \n");


for (i = 1; i <= n; i++) {
scanf("%d", &p[i]);
}

printf("Weight Array : \n");


for (i = 1; i <= n; i++) {
scanf("%d", &w[i]);
}
knapsack();
return 0;
}

14 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

7. Design and implement C/C++ Program to solve discrete Knapsack and


continuous Knapsack problems using greedy approximation method.

#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,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);
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 problems using Greedy Algorithm:\n");


for (i = 0; i < n; i++)
{
if (weight[i] > capacity)

15 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}

16 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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.

#include <stdlib.h>
#include <stdio.h>

int *w, n, m, *sel;


void print_soln()
{
int i;
printf("Soln : ");
for (i = 0; i < n; i++)
{
if (sel[i] == 1)
{
printf("%d ", w[i]);
}
}
printf("\n");
}
void subset_sum(int ssf, int index)
{
if (ssf + w[index] <= m)
{
sel[index] = 1;
if (ssf + w[index] == m)
{
print_soln();
}
else
{
subset_sum(ssf + w[index], index + 1);
}
sel[index] = 0;
subset_sum(ssf, index + 1);
}
}

int main()
{
int i;

17 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

printf("Number of elements : ");


scanf("%d", &n);

w = calloc(n, sizeof(int));
sel = calloc(n, sizeof(int));

printf("The elements : \n");


for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}

printf("Desired Sum : ");


scanf("%d", &m);
subset_sum(0, 0);
return 0;
}

18 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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>
// Function to perform selection sort on an array
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i; // Assume the current element is the minimum
for (j = i+1; j < n; j++)
{
if (arr[j] < arr[min_idx])
{
min_idx = j; // Update min_idx if a smaller element is found
}
}
// Swap the found minimum element with the current element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Function to generate an array of random numbers
void generateRandomNumbers(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 10000; // Generate random numbers between 0 and 9999
}
}

int main()
{
int n, arr[100],i;
printf("Enter number of elements: ");

19 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

scanf("%d", &n); // Read the number of elements from the user

//if(n <= 5000)


{
// printf("Please enter a value greater than 5000\n");
// return 1; // Exit if the number of elements is not greater than 5000
}

printf("\nEnter the array:");


for(i=0;i<n;i++)
scanf(“%d”,&arr[i]); // Generate random numbers and store them in the array
generateRandomNumbers(arr, n);

// Measure the time taken to sort the array


clock_t start = clock();
selectionSort(arr, n);
clock_t end = clock();

// Calculate and print the time taken to sort the array


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);

// Free the allocated memory


free(arr);
return 0;
}

20 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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 <stdlib.h>
#include <stdio.h>
#include <time.h>

int *a, n;
int partition(int l, int r)
{
int i, j, p, temp;
i = l;
j = r + 1;
p = a[l];
while (i <= j)
{
do
{
i++;
} while (p >= a[i]);
do
{
j--;
} while (p < a[j]);

if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

temp = a[l];
a[l] = a[j];
a[j] = temp;
return j;
}

21 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

void q_sort(int l, int r)


{
int s;
if (l < r)
{
s = partition(l, r);
q_sort(l, s - 1);
q_sort(s + 1, r);
}
}

void print_array()
{
int i;
for (i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
printf("\n");
}

int main()
{
int i;
float start, end, complexity;
printf("Enter the value of n : ");
scanf("%d", &n);
a = calloc(n, sizeof(int));
for (i = 0; i < n; i++)
{
a[i] = rand() % 20;
}
printf("The array is : \n");
print_array();
start = clock();
q_sort(0, n - 1);
end = clock();
printf("The sorted array is : \n");
print_array();

22 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

complexity = (end - start) / CLOCKS_PER_SEC;


printf("Start time = %f \n", start);
printf("End time = %f \n", end);
printf("Complexity = %f \n", complexity);
return 0;
}

23 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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>

// Function to merge two sorted arrays


void merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

int *L = (int *)malloc(n1 * sizeof(int));


int *R = (int *)malloc(n2 * sizeof(int));

for (i = 0; i < n1; i++)


L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

i = 0;
j = 0;
k = left;

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1)


{
arr[k] = L[i];

24 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

i++;
k++;
}

while (j < n2)


{
arr[k] = R[j];
j++;
k++;
}

free(L);
free(R);
}

// Function to implement Merge Sort


void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

// Function to generate random integers


void generateRandomArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
arr[i] = rand() % 100000; // Generate random integers between 0 and 99999
}

int main()
{
int ni, arr[100];
printf("Enter the number of elements: ");
scanf("%d", &n);

if (n <= 5000)
{
printf("Please enter a value greater than 5000\n");
return 1; // Exit if the number of elements is not greater than 5000
}
printf("\nEnter the array:");

25 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);

generateRandomArray(arr, n);

// Repeat the sorting process multiple times to increase duration for timing
clock_t start = clock();
for (int i = 0; i < 1000; i++)
{
mergeSort(arr, 0, n - 1);
}
clock_t end = clock();

// Calculate the time taken for one iteration


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC / 1000.0;

printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);

return 0;
}

26 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

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

#include <stdlib.h>
#include <stdio.h>

int *x, q = 0, n;

int can_place(int p)
{
int i;
for (i = 0; i < q; i++)
{
if (x[i] == p || x[i] - i == p - q || x[i] + i == p + q)
{
return 0;
}
}
return 1;
}
void print_board()
{
int i, j;
printf("Solution : \n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (x[i] == j)
{
printf("Q ");
}
else
{
printf("_ ");
}
}
printf("\n");
}
}

27 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT


Analysis & Design of Algorithms Lab 2023

void n_queens()
{
int p;
for (p = 0; p < n; p++)
{
if (can_place(p))
{
x[q] = p;
q++;
if (q == n)
{
print_board();
}
else
{
n_queens();
}
q--;
}
}
}
int main()
{
printf("Board size : ");
scanf("%d", &n);
x = calloc(n, sizeof(int));
n_queens();
return 0;
}

28 Prepared By Kiran Kumar P N, Asst. Professor, Dept. of CSE, SJCIT

You might also like