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

ADA Manual - Cprogramming

lab manual Algorithms

Uploaded by

Ms Anushree G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

ADA Manual - Cprogramming

lab manual Algorithms

Uploaded by

Ms Anushree G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Analysis & design of algorithms Lab(BCSL404) Academic Year: 2023-24

CMR INSTITUTE OF TECHNOLOGY


Department of Artificial Intelligence and DataScience

LAB MANUAL

ANALYSIS & DESIGN OF ALGORITHMS LABORATORY


(BCSL404)
Semester-IV

Academic Year: 2023-2024

Analysis & design of algorithms Lab(BCSL404)


1 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404) Academic Year: 2023-24

Syllabus
Part-A-
List of problems for which student should develop program and execute in the
Laboratory

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

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

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

b. Design and implement C/C++ Program to find the transitive closure using Warshal's algorithm.

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.

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

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

7. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack 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 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.

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.

Analysis & design of algorithms Lab(BCSL404)


2 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404) Academic Year: 2023-24
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.

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

Analysis & design of algorithms Lab(BCSL404)


3 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24
Program-1: Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
given connected undirected graph using Kruskal's algorithm.

Algorithm:
1. Sort all the edges of the graph in non-decreasing order of their weights.
2. Initialize an empty set to store the minimum spanning tree (MST).
3. Initialize an array to track the parent of each vertex in the graph. Initially, each vertex is its own parent.
4. Iterate through all the sorted edges:
a. Pick the smallest edge.
b. Check if including this edge forms a cycle in the MST. If adding this edge creates a cycle, skip it.
c. If adding this edge does not create a cycle, add it to the MST and update the parent array to merge the subsets.
5. Repeat step 4 until there are V-1 edges in the MST, where V is the number of vertices in the graph.
6. The MST is now found. Output the edges of the MST.

// C code to implement Kruskal's algorithm

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

// Comparator function to use in sorting


int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];


}

// Initialization of parent[] and rank[] arrays


void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}

// Function to find the parent of a node


int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;

return parent[component]
= findParent(parent, parent[component]);
}

// Function to unite two sets


void unionSet(int u, int v, int parent[], int rank[], int n)

Analysis & design of algorithms Lab(BCSL404)


4 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
{ Academic Year: 2023-24
// Finding the parents
u = findParent(parent, u);
v = findParent(parent, v);

if (rank[u] < rank[v]) {


parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;

// Since the rank increases if


// the ranks of two sets are same
rank[u]++;
}
}

// Function to find the MST


void kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];
int rank[n];

// Function to initialize parent[] and rank[]


makeSet(parent, rank, n);

// To store the minimun cost


int minCost = 0;

printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];

// If the parents are different that


// means they are in different sets so
// union them
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}

Analysis & design of algorithms Lab(BCSL404)


5 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
printf("Minimum Cost Spanning Tree: %d\n", minCost); Academic Year: 2023-24
}

// Driver code
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };

kruskalAlgo(5, edge);

return 0;
}

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

// A C program for Prim's Minimum


// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

// A utility function to print the


Analysis & design of algorithms Lab(BCSL404)
6 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
// constructed MST stored in parent[] Academic Year: 2023-24
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
}

// Function to construct and print MST for


// a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];
// Key values used to pick minimum weight edge in cut
int key[V];
// To represent set of vertices included in MST
bool mstSet[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; 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 graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
Analysis & design of algorithms Lab(BCSL404)
7 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
&& graph[u][v] < key[v]) Academic Year: 2023-24
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}

// Driver's code
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}

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

b. Design and implement C/C++ Program to find the transitive closure using Warshal's algorithm.

3a.
// C Program for Floyd Warshall Algorithm
#include <stdio.h>

// Number of vertices in the graph


#define V 4

/* Define Infinite as a large enough


value. This value will be used
for vertices not connected to each other */
#define INF 99999

// A function to print the solution matrix


void printSolution(int dist[][V]);

// Solves the all-pairs shortest path


// problem using Floyd Warshall algorithm
void floydWarshall(int dist[][V])
{
int i, j, k;

/* Add all vertices one by one to


the set of intermediate vertices.
---> Before start of an iteration, we
Analysis & design of algorithms Lab(BCSL404)
8 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
have shortest distances between all Academic Year: 2023-24
pairs of vertices such that the shortest
distances consider only the
vertices in set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of an iteration,
vertex no. k is added to the set of
intermediate vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of
// dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

// Print the shortest distance matrix


printSolution(dist);
}

/* A utility function to print solution */


void printSolution(int dist[][V])
{
printf(
"The following matrix shows the shortest distances"
" between every pair of vertices \n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

// driver's code
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5| |
| |1
Analysis & design of algorithms Lab(BCSL404)
9 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
\|/ | Academic Year: 2023-24
(1)------->(2)
3 */
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };

// Function call
floydWarshall(graph);
return 0;
}

3b.

// Program for transitive closure


// using Floyd Warshall Algorithm
#include<stdio.h>

// Number of vertices in the graph


#define V 4

// A function to print the solution matrix


void printSolution(int reach[][V]);

// Prints transitive closure of graph[][]


// using Floyd Warshall algorithm
void transitiveClosure(int graph[][V])
{
/* reach[][] will be the output matrix
// that will finally have the
shortest distances between
Analysis & design of algorithms Lab(BCSL404)
10 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
every pair of vertices */ Academic Year: 2023-24
int reach[V][V], i, j, k;

/* Initialize the solution matrix same


as input graph matrix. Or
we can say the initial values of
shortest distances are based
on shortest paths considering
no intermediate vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
reach[i][j] = graph[i][j];

/* Add all vertices one by one to the


set of intermediate vertices.
---> Before start of a iteration,
we have reachability values for
all pairs of vertices such that
the reachability values
consider only the vertices in
set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of a iteration,
vertex no. k is added to the
set of intermediate vertices
and the set becomes {0, 1, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as
// source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as
// destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on a path
// from i to j,
// then make sure that the value
// of reach[i][j] is 1
reach[i][j] = reach[i][j] ||
(reach[i][k] && reach[k][j]);
}
}
}

// Print the shortest distance matrix


printSolution(reach);
}

/* A utility function to print solution */


void printSolution(int reach[][V])
{
Analysis & design of algorithms Lab(BCSL404)
11 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
printf ("Following matrix is transitive"); Academic Year: 2023-24
printf("closure of the given graph\n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
/* because "i==j means same vertex"
and we can reach same vertex
from same vertex. So, we print 1....
and we have not considered this in
Floyd Warshall Algo. so we need to
make this true by ourself
while printing transitive closure.*/
if(i == j)
printf("1 ");
else
printf ("%d ", reach[i][j]);
}
printf("\n");
}
}

// Driver Code
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5| |
| |1
\|/ |
(1)------->(2)
3 */
int graph[V][V] = { {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};

// Print the solution


transitiveClosure(graph);
return 0;
}

Analysis & design of algorithms Lab(BCSL404)


12 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24

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.
// C program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 9

// A utility function to find the vertex with minimum


// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance


// array
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source


// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is


// included in shortest
// path tree or shortest distance from src to i is
// finalized
Analysis & design of algorithms Lab(BCSL404)
13 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24
// Initialize all distances as INFINITE and stpSet[] as
// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed. u is always equal to
// src in the first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet,


// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[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];
}

// print the constructed distance array


printSolution(dist);
}

// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

// Function call
dijkstra(graph, 0);

Analysis & design of algorithms Lab(BCSL404)


14 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
return 0; Academic Year: 2023-24
}

Analysis & design of algorithms Lab(BCSL404)


15 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic
5. Design and implement C/C++ Program to obtain the Topological ordering Year:
of vertices in a2023-24
given digraph.

/*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;
}
Analysis & design of algorithms Lab(BCSL404)
16 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
} Academic Year: 2023-24
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]);
}

Analysis & design of algorithms Lab(BCSL404)


17 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
6. Design and implement C/C++ Program to solve 0/1 Knapsack problem Academic Year:Programming
using Dynamic 2023-24
method.
// Here is the top-down approach of
// dynamic programming
#include <bits/stdc++.h>
using namespace std;

// Returns the value of maximum profit


int knapSackRec(int W, int wt[], int val[], int index, int** dp)
{
// base condition
if (index < 0)
return 0;
if (dp[index][W] != -1)
return dp[index][W];

if (wt[index] > W) {

// Store the value of function call


// stack in table before return
dp[index][W] = knapSackRec(W, wt, val, index - 1, dp);
return dp[index][W];
}
else {
// Store value in a table before return
dp[index][W] = max(val[index]
+ knapSackRec(W - wt[index], wt, val,
index - 1, dp),
knapSackRec(W, wt, val, index - 1, dp));

// Return value of table after storing


return dp[index][W];
}
}

int knapSack(int W, int wt[], int val[], int n)


{
// double pointer to declare the
// table dynamically
int** dp;
dp = new int*[n];

// loop to create the table dynamically


for (int i = 0; i < n; i++)
dp[i] = new int[W + 1];

// loop to initially filled the


// table with -1
for (int i = 0; i < n; i++)
for (int j = 0; j < W + 1; j++)
dp[i][j] = -1;
return knapSackRec(W, wt, val, n - 1, dp);

Analysis & design of algorithms Lab(BCSL404)


18 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
} Academic Year: 2023-24

// Driver Code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}

7. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack problems
using 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++)

Analysis & design of algorithms Lab(BCSL404)


19 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
{ Academic Year: 2023-24

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)


Analysis & design of algorithms Lab(BCSL404)
20 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
{ Academic Year: 2023-24

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]);
Analysis & design of algorithms Lab(BCSL404)
21 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
printf("Enter the objects' profits: "); Academic Year: 2023-24

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;

Analysis & design of algorithms Lab(BCSL404)


22 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24

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.

/* 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("Enter the no. of elements: ");
scanf("%d",&n);
printf("\nEnter the elements in ascending order:\n");
for(i=0;i<n;i++)
scanf("%d",&w[i]);
printf("\nEnter the sum: ");
scanf("%d",&d);
for(i=0;i<n;i++)
sum=sum+w[i];
if(sum<d)
{
printf("No solution\n");
getch();
return;
}
subset(0,0,sum);
if(count==0)
{
printf("No solution\n");
getch();
return;
}
getch();
}
void subset(int cs,int k,int r)
{
int i;
x[k]=1;
if(cs+w[k]==d)
{
printf("\n\nSubset %d\n",++count);
for(i=0;i<=k;i++)
if(x[i]==1)
printf("%d\t",w[i]);
}
Analysis & design of algorithms Lab(BCSL404)
23 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
else if(cs+w[k]+w[k+1]<=d) Academic Year: 2023-24
subset(cs+w[k],k+1,r-w[k]);
if(cs+r-w[k]>=d && cs+w[k]<=d)
{
x[k]=0;
subset(cs,k+1,r-w[k]);
}
}

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.
// C program for implementation of selection sort
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function to perform selection sort


void selectionSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int min_idx = i;
for (int 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;
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
FILE *fptr;
fptr = fopen("selection_sort_results.csv", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
Analysis & design of algorithms Lab(BCSL404)
24 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24
srand(time(0));
fprintf(fptr, "Number of Elements,Time Taken (seconds)\n");

for (int n = 5000; n <= 50000; n += 5000) {


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}

for (int i = 0; i < n; i++) {


arr[i] = rand();
}

clock_t start, end;


double cpu_time_used;

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

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

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


fprintf(fptr, "%d,%f\n", n, cpu_time_used);

free(arr);
}

fclose(fptr);
return 0;
}

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>

void swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = t;
}

int partition(int arr[], int low, int high) {


Analysis & design of algorithms Lab(BCSL404)
25 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
int pivot = arr[high]; Academic Year: 2023-24
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
FILE *fptr;
fptr = fopen("results.csv", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}

srand(time(0));

fprintf(fptr, "Number of Elements,Time Taken (seconds)\n");

for (int n = 5000; n <= 50000; n += 5000) {


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}

Analysis & design of algorithms Lab(BCSL404)


26 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
for (int i = 0; i < n; i++) { Academic Year: 2023-24
arr[i] = rand();
}

clock_t start, end;


double cpu_time_used;

start = clock();
quickSort(arr, 0, n - 1);
end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

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


fprintf(fptr, "%d,%f\n", n, cpu_time_used);

free(arr);
}

fclose(fptr);
return 0;
}

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 halves of an array


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

int L[n1], R[n2];

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


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

int i = 0, j = 0, k = left;
Analysis & design of algorithms Lab(BCSL404)
27 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
while (i < n1 && j < n2) { Academic Year: 2023-24
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


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

// Function to perform 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 print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
//arr[i]=rand();
}
printf("\n");
}

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

int *arr = (int *)malloc(n * sizeof(int));


if (arr == NULL) {
printf("Memory not allocated.\n");
Analysis & design of algorithms Lab(BCSL404)
28 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
exit(0); Academic Year: 2023-24
}

printf("Enter %d integers: ", n);


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

printf("Given array: \n");


printArray(arr, n);

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


printArray(arr, n);

printf("Time taken to sort the array: %f seconds\n", cpu_time_used);

free(arr);
return 0;
}

Part2
int main() {
FILE *fptr;
fptr = fopen("merge_sort_results.csv", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}

srand(time(0));
fprintf(fptr, "Number of Elements,Time Taken (seconds)\n");

for (int n = 5000; n <= 50000; n += 5000) {


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory not allocated.\n");
exit(0);
Analysis & design of algorithms Lab(BCSL404)
29 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
} Academic Year: 2023-24

for (int i = 0; i < n; i++) {


arr[i] = rand();
}

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("Time taken to sort %d elements: %f seconds\n", n, cpu_time_used);


fprintf(fptr, "%d,%f\n", n, cpu_time_used);

free(arr);
}

fclose(fptr);
return 0;
}

Analysis & design of algorithms Lab(BCSL404)


30 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
Academic Year: 2023-24

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

/* 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();
printf("Enter the no.of queens: ");
scanf("%d",&n);
nqueens(n);
getch();
}
void nqueens(int n)
{
int x[10],count=0,k=1;
x[k]=0;
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;
}
Analysis & design of algorithms Lab(BCSL404)
31 ANUSHREE G
Analysis & design of algorithms Lab(BCSL404)
} Academic Year: 2023-24
else
{
k--; //backtracking
}
}
return;
}

int place(int x[],int k)


{
int i;
for(i=1;i<k;i++)
if(x[i]==x[k]||(abs(x[i]-x[k]))==abs(i-k))
return 0;
return 1;
}
void printsolution(int n,int x[])
{
int i,j;
char c[10][10];
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
c[i][j]='X';
}
for(i=1;i<=n;i++)
c[i][x[i]]='Q';
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%c\t",c[i][j]);
}
printf("\n");
}

Analysis & design of algorithms Lab(BCSL404)


32 ANUSHREE G

You might also like