0% found this document useful (0 votes)
5 views37 pages

Algorithm Lab Manual

The document is a laboratory manual for the Analysis & Design of Algorithms course at SJC Institute of Technology, detailing practical experiments and objectives for students. It includes various algorithm implementations in C/C++, assessment criteria, and evaluation methods for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE). The manual aims to equip students with skills to design, implement, and analyze algorithms effectively.
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)
5 views37 pages

Algorithm Lab Manual

The document is a laboratory manual for the Analysis & Design of Algorithms course at SJC Institute of Technology, detailing practical experiments and objectives for students. It includes various algorithm implementations in C/C++, assessment criteria, and evaluation methods for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE). The manual aims to equip students with skills to design, implement, and analyze algorithms effectively.
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/ 37

|| Jai Sri Gurudev ||

Adichunchanagiri Shikshana Trust(R.)


SJC INSTITUTE OF TECHNOLOGY

Department of Artificial Intelligence & Machine Learning

LABORATORY MANUAL

ANALYSIS & DESIGN OF ALGORITHMS [BCSL404]

Prepared by

Dr.Vikas Reddy. S
Associate Professor & Head
Department of Artificial Intelligence & Machine Learning
SJC Institute of Technology

2025
Template for Practical Course and if AEC is a practical Course Annexure-V

Analysis & Design of Algorithms Lab Semester 4


Course Code BCSL404 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Credits 01 Exam Hours 2
Examination type (SEE) Practical
Course objectives:
● To design and implement various algorithms in C/C++ programming using suitable development tools to
address different computational challenges.
● To apply diverse design strategies for effective problem-solving.
● To Measure and compare the performance of different algorithms to determine their efficiency and suitability
for specific tasks.
Sl.No Experiments
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.
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.

@# 16032024
Template for Practical Course and if AEC is a practical Course Annexure-V

Course outcomes (Course Skill Set):


At the end of the course the student will be able to:
1. Develop programs to solve computational problems using suitable algorithm design strategy.
2. Compare algorithm design strategies by developing equivalent programs and observing running
times for analysis (Empirical).
3. Make use of suitable integrated development tools to develop programs
4. Choose appropriate algorithm design techniques to develop solution to the computational and
complex problems.
5. Demonstrate and present the development of program, its execution and running time(s) and
record the results/inferences.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be
deemed to have satisfied the academic requirements and earned the credits allotted to each subject/
course if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE
(Continuous Internal Evaluation) and SEE (Semester End Examination) taken together

Continuous Internal Evaluation (CIE):


CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments are
designed by the faculty who is handling the laboratory session and are made known to students at
the beginning of the practical session.
● Record should contain all the specified experiments in the syllabus and each experiment write-up
will be evaluated for 10 marks.
● Total marks scored by the students are scaled down to 30 marks (60% of maximum marks).
● Weightage to be given for neatness and submission of record/write-up on time.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed in
the syllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge will
carry a weightage of 60% and the rest 40% for viva-voce.
● The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
● The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is the total CIE
marks scored by the student.

Semester End Evaluation (SEE):


● SEE marks for the practical course are 50 Marks.

@# 16032024
Template for Practical Course and if AEC is a practical Course Annexure-V

● SEE shall be conducted jointly by the two examiners of the same institute, examiners are
appointed by the Head of the Institute.
● The examination schedule and names of examiners are informed to the university before the
conduction of the examination. These practical examinations are to be conducted between the
schedule mentioned in the academic calendar of the University.
● All laboratory experiments are to be included for practical examination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script
to be strictly adhered to by the examiners. OR based on the course requirement evaluation
rubrics shall be decided jointly by examiners.
● Students can pick one question (experiment) from the questions lot prepared by the examiners
jointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.
● General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and
result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks
and scored marks shall be scaled down to 50 marks (however, based on course type, rubrics shall be
decided by the examiners)
● Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to be
made zero.
The minimum duration of SEE is 02 hours

Suggested Learning Resources:


● Virtual Labs (CSE): http://cse01-iiith.vlabs.ac.in/

@# 16032024
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>

#define MAX 100

// Structure to represent an edge


struct Edge {
int u, v, weight;
};

// Structure to represent the graph


struct Graph {
int V, E;
struct Edge edges[MAX];
};

// Find the root (or parent) of a vertex


int find(int parent[], int i) {
if (parent[i] == i)
return i;
return find(parent, parent[i]);
}

// Perform the union of two subsets


void unionSets(int parent[], int rank[], int x, int y) {
int rootX = find(parent, x);
int rootY = find(parent, y);

if (rank[rootX] < rank[rootY])


parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else {
parent[rootY] = rootX;
rank[rootX]++;
}
}

// Comparison function to sort edges by weight


int compareEdges(const void* a, const void* b) {
struct Edge* edge1 = (struct Edge*)a;
struct Edge* edge2 = (struct Edge*)b;
return edge1->weight - edge2->weight;
}

Dept. of AI&ML, SJCIT 1


// Kruskal's Algorithm to find MST
void kruskalMST(struct Graph* graph) {
int V = graph->V;
struct Edge result[MAX]; // To store the resulting MST
int parent[MAX], rank[MAX];

// Initialize parent and rank arrays


for (int i = 0; i < V; i++) {
parent[i] = i;
rank[i] = 0;
}

// Sort all edges by weight


qsort(graph->edges, graph->E, sizeof(graph->edges[0]),
compareEdges);

int e = 0, i = 0; // e: Number of edges in MST, i: Index


of the next edge
while (e < V - 1 && i < graph->E) {
struct Edge nextEdge = graph->edges[i++];

int x = find(parent, nextEdge.u);


int y = find(parent, nextEdge.v);

if (x != y) { // If adding this edge doesn't form a


cycle
result[e++] = nextEdge;
unionSets(parent, rank, x, y);
}
}

// Print the resulting MST


printf("Edges in the Minimum Spanning Tree:\n");
int totalWeight = 0;
for (int j = 0; j < e; j++) {
printf("%d -- %d == %d\n", result[j].u, result[j].v,
result[j].weight);
totalWeight += result[j].weight;
}
printf("Total cost of MST: %d\n", totalWeight);
}

// Main function
int main() {
struct Graph graph;
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &graph.V, &graph.E);

printf("Enter the edges (u v weight):\n");

Dept. of AI&ML, SJCIT 2


for (int i = 0; i < graph.E; i++) {
scanf("%d %d %d", &graph.edges[i].u,
&graph.edges[i].v, &graph.edges[i].weight);
}

kruskalMST(&graph);
return 0;
}

Output

Enter the number of vertices and edges: 4 5


Enter the edges (u v weight):
0 1 10
0 2 6
0 3 5
1 3 15
2 3 4
Edges in the Minimum Spanning Tree:
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Total cost of MST: 19
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 3


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

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

#define MAX 100

// Function to find the vertex with the minimum key value


int minKey(int key[], bool mstSet[], int V) {
int min = INT_MAX, minIndex;

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


if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}

// Function to print the constructed MST


void printMST(int parent[], int graph[MAX][MAX], int V) {
printf("Edges in the Minimum Spanning Tree:\n");
int totalWeight = 0;
for (int i = 1; i < V; i++) {
printf("%d -- %d == %d\n", parent[i], i, graph[i]
[parent[i]]);
totalWeight += graph[i][parent[i]];
}
printf("Total cost of MST: %d\n", totalWeight);
}

// Prim's Algorithm for Minimum Spanning Tree


void primMST(int graph[MAX][MAX], int V) {
int parent[MAX]; // Stores the MST
int key[MAX]; // Key values to pick the minimum weight
edge
bool mstSet[MAX]; // To track vertices included in MST

// Initialize key values as infinite and mstSet[] as false


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

key[0] = 0; // Start from the first vertex


parent[0] = -1; // First node is the root of the MST

Dept. of AI&ML, SJCIT 4


for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V);
mstSet[u] = true;

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


if (graph[u][v] && !mstSet[v] && graph[u][v] <
key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph, V);
}

int main() {
int V;
printf("Enter the number of vertices: ");
scanf("%d", &V);

int graph[MAX][MAX];
printf("Enter the adjacency matrix (use 0 for no edge):
\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}

primMST(graph, V);
return 0;
}

Output

Enter the number of vertices: 4


Enter the adjacency matrix (use 0 for no edge):
0 10 6 5
10 0 0 15
6 0 0 4
5 15 4 0
Edges in the Minimum Spanning Tree:
0 -- 1 == 10
3 -- 2 == 4
0 -- 3 == 5
Total cost of MST: 19
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 5


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

#include <stdio.h>
#define INF 99999 // A large value to represent infinity
#define V 4 // Number of vertices in the graph

// Function to implement Floyd-Warshall Algorithm


void floydWarshall(int graph[V][V]) {
int dist[V][V];

// Initialize the solution matrix same as input graph


matrix
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}

// Update distances considering each vertex as an


intermediate
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF &&
dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

// Print the shortest distance matrix


printf("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("INF ");
else
printf("%d ", dist[i][j]);
}
printf("\n");
}
}

int main() {
int graph[V][V] = {
{0, 3, INF, 5},

Dept. of AI&ML, SJCIT 6


{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}
};

floydWarshall(graph);
return 0;
}

Output

Shortest distances between every pair of vertices:


0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0

Dept. of AI&ML, SJCIT 7


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

#include <stdio.h>
#define V 4 // Number of vertices in the graph

// Function to implement Warshall's Algorithm for transitive


closure
void warshallAlgorithm(int graph[V][V]) {
int reach[V][V];

// Initialize reachability matrix same as the input


adjacency matrix
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
reach[i][j] = graph[i][j];
}
}

// Compute transitive closure


for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
reach[i][j] = reach[i][j] || (reach[i][k] &&
reach[k][j]);
}
}
}

// Print the transitive closure matrix


printf("Transitive Closure of the given graph:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", reach[i][j]);
}
printf("\n");
}
}

int main() {
int graph[V][V] = {
{0, 1, 0, 0},
{0, 0, 0, 1},
{0, 0, 0, 0},
{1, 0, 1, 0}
};

Dept. of AI&ML, SJCIT 8


warshallAlgorithm(graph);
return 0;
}

Output

Transitive Closure of the given graph:


1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1

Dept. of AI&ML, SJCIT 9


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 <limits.h>
#define V 5 // Number of vertices in the graph

// Function to find the vertex with the minimum distance value


int minDistance(int dist[], int visited[]) {
int min = INT_MAX, min_index;

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


if (!visited[v] && dist[v] <= min) {
min = dist[v], min_index = v;
}
}
return min_index;
}

// Function to implement Dijkstra's Algorithm


void dijkstra(int graph[V][V], int src) {
int dist[V]; // Stores shortest distance from src to i
int visited[V]; // visited[i] is true if vertex i is
processed

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


dist[i] = INT_MAX;
visited[i] = 0;
}

dist[src] = 0;

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


int u = minDistance(dist, visited);
visited[u] = 1;

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


if (!visited[v] && graph[u][v] && dist[u] !=
INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

printf("Vertex \t Distance from Source\n");


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

Dept. of AI&ML, SJCIT 10


}

int main() {
int graph[V][V] = {
{0, 10, 3, 0, 0},
{10, 0, 1, 2, 4},
{3, 1, 0, 0, 8},
{0, 2, 0, 0, 5},
{0, 4, 8, 5, 0}
};

int src = 0; // Starting vertex


dijkstra(graph, src);

return 0;
}

Output
Vertex Distance from Source
0 0
1 4
2 3
3 6
4 8
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 11


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

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

#define MAX 100 // Maximum number of vertices

int adj[MAX][MAX]; // Adjacency matrix


int visited[MAX]; // Array to track visited vertices
int stack[MAX], top = -1; // Stack for storing topological
order
int n; // Number of vertices

// Function to perform DFS and push nodes to stack


void dfs(int v) {
visited[v] = 1;
for (int i = 0; i < n; i++) {
if (adj[v][i] && !visited[i]) {
dfs(i);
}
}
stack[++top] = v; // Push vertex to stack after visiting
all its neighbors
}

// Function to perform topological sorting using DFS


void topologicalSort() {
for (int i = 0; i < n; i++) {
visited[i] = 0;
}

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


if (!visited[i]) {
dfs(i);
}
}

printf("Topological Order: ");


while (top >= 0) {
printf("%d ", stack[top--]);
}
printf("\n");
}

int main() {
printf("Enter number of vertices: ");
scanf("%d", &n);

Dept. of AI&ML, SJCIT 12


printf("Enter adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &adj[i][j]);
}
}

topologicalSort();

return 0;
}

Output
Enter number of vertices: 5

Enter adjacency matrix:

0 0 1 0 0
0 0 1 0 0
0 0 0 1 1
0 0 0 0 1
0 0 0 0 0

Topological Order: 1 0 2 3 4

Dept. of AI&ML, SJCIT 13


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 capacity, int weights[], int values[], int n)


{
int dp[capacity + 1];
for (int i = 0; i <= capacity; i++)
dp[i] = 0;

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


for (int w = capacity; w >= weights[i]; w--) {
dp[w] = max(dp[w], values[i] + dp[w -
weights[i]]);
}
}
return dp[capacity];
}

int main() {
int n, capacity;
printf("Enter number of items: ");
scanf("%d", &n);
int weights[n], values[n];

printf("Enter profits followed by weights:\n");


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

printf("Enter knapsack capacity: ");


scanf("%d", &capacity);

printf("Maximum value: %d\n", knapsack(capacity, weights,


values, n));

return 0;
}

Dept. of AI&ML, SJCIT 14


Output
Enter number of items: 4
Enter profits followed by weights:
78 2
45 3
92 4
71 5
Enter knapsack capacity: 6
Maximum value: 170

Dept. of AI&ML, SJCIT 15


7.Design and implement C/C++ Program to solve discrete Knapsack and
continuous Knapsack problems using greedy approximation method.

#include <stdio.h>

struct Item {
int weight;
int profit;
int index; // Original item number
};

// Calculate profit/weight ratio


float ratio(struct Item item) {
return (float)item.profit / item.weight;
}

// Sort items by profit/weight ratio (descending)


void sortItems(struct Item items[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (ratio(items[j]) > ratio(items[i])) {
struct Item temp = items[i];
items[i] = items[j];
items[j] = temp;
}
}
}
}

// Fractional Knapsack
float fractionalKnapsack(struct Item items[], int n, int
capacity) {
float totalProfit = 0.0;

printf("\nItems included in Fractional Knapsack:\n");

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


if (items[i].weight <= capacity) {
capacity -= items[i].weight;
totalProfit += items[i].profit;
printf("Item %d: 100%% of profit = %d\n",
items[i].index + 1, items[i].profit);
} else {
float fraction = (float)capacity /
items[i].weight;
float fracProfit = items[i].profit * fraction;
totalProfit += fracProfit;
printf("Item %d: %.2f%% of profit = %.2f\n",
items[i].index + 1, fraction * 100, fracProfit);

Dept. of AI&ML, SJCIT 16


break;
}
}

return totalProfit;
}

// Discrete Knapsack (Greedy)


int discreteKnapsack(struct Item items[], int n, int capacity)
{
int totalProfit = 0;

printf("\nItems included in 0/1 Knapsack (Greedy Approx):


\n");

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


if (items[i].weight <= capacity) {
capacity -= items[i].weight;
totalProfit += items[i].profit;
printf("Item %d: Taken, profit = %d\n",
items[i].index + 1, items[i].profit);
}
}

return totalProfit;
}

int main() {
int n, capacity;

// Input
printf("Enter number of items: ");
scanf("%d", &n);

struct Item items[n];

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


printf("Enter weight and profit of item %d: ", i + 1);
scanf("%d %d", &items[i].weight, &items[i].profit);
items[i].index = i;
}

printf("Enter knapsack capacity: ");


scanf("%d", &capacity);

// Sort items by profit/weight ratio


sortItems(items, n);

// Create copies for independent calculations

Dept. of AI&ML, SJCIT 17


struct Item itemsCopy[n];
for (int i = 0; i < n; i++) {
itemsCopy[i] = items[i];
}

int capacityCopy = capacity;

// Solve both problems


float fracProfit = fractionalKnapsack(items, n, capacity);
int discProfit = discreteKnapsack(itemsCopy, n,
capacityCopy);

// Output
printf("\n--- Final Results ---\n");
printf("Total Profit (Fractional Knapsack): %.2f\n",
fracProfit);
printf("Total Profit (0/1 Knapsack - Greedy Approx):
%d\n", discProfit);

return 0;
}

Output
Enter number of items: 3
Enter weight and profit of item 1: 20 100
Enter weight and profit of item 2: 10 60
Enter weight and profit of item 3: 30 120
Enter knapsack capacity: 50

Items included in Fractional Knapsack:


Item 2: 100% of profit = 60
Item 1: 100% of profit = 100
Item 3: 66.67% of profit = 80.00

Items included in 0/1 Knapsack (Greedy Approx):


Item 2: Taken, profit = 60
Item 1: Taken, profit = 100

--- Final Results ---


Total Profit (Fractional Knapsack): 240.00
Total Profit (0/1 Knapsack - Greedy Approx): 160
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 18


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 <stdio.h>

int found = 0;

void subsetSum(int set[], int n, int d, int index, int


currentSum, int subset[]) {
if (currentSum == d) {
printf("Subset found: ");
for (int i = 0; i < index; i++) {
if (subset[i])
printf("%d ", set[i]);
}
printf("\n");
found = 1;
return;
}

if (currentSum > d || index == n)


return;

// Include set[index]
subset[index] = 1;
subsetSum(set, n, d, index + 1, currentSum + set[index],
subset);

// Exclude set[index]
subset[index] = 0;
subsetSum(set, n, d, index + 1, currentSum, subset);
}

int main() {
int set[100], n, d;

printf("Enter number of elements in 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 desired sum: ");


scanf("%d", &d);

Dept. of AI&ML, SJCIT 19


int subset[100] = {0};
subsetSum(set, n, d, 0, 0, subset);

if (!found)
printf("No subset found with the given sum.\n");

return 0;
}

Output

Sample 1:

Enter number of elements in set: 5


Enter the elements of the set:
1 2 4 6 8
Enter the desired sum: 9
Subset found: 1 2 6
Subset found: 1 8
Program ended with exit code: 0

Sample 2:

Enter number of elements in set: 5


Enter the elements of the set:
1 2 4 6 8
Enter the desired sum: 33
No subset found with the given sum.
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 20


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, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min])
min = j;
}
// Swap
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}

int main() {
int n;
printf("Enter number of elements (n > 5000 recommended):
");
scanf("%d", &n);

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


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Generate random numbers


for (int i = 0; i < n; i++) {
arr[i] = rand() % 10000; // numbers between 0 and
9999
}

// Measure time
clock_t start = clock();

selectionSort(arr, n);

Dept. of AI&ML, SJCIT 21


clock_t end = clock();

double time_taken = ((double)(end - start)) /


CLOCKS_PER_SEC;

printf("Time taken to sort %d elements using Selection


Sort: %.5f seconds\n", n, time_taken);

free(arr);
return 0;
}

Output

Sample 1:

Enter number of elements (n > 5000 recommended): 6000


Time taken to sort 6000 elements using Selection Sort: 0.04891
seconds
Program ended with exit code: 0

Sample 2:

Enter number of elements (n > 5000 recommended): 9000


Time taken to sort 9000 elements using Selection Sort: 0.07512
seconds
Program ended with exit code: 0

Sample 3:
Enter number of elements (n > 5000 recommended): 25000
Time taken to sort 25000 elements using Selection Sort:
0.39842 seconds
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 22


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>

// Function to swap two integers


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Pivot element
int i = low - 1;

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


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

swap(&arr[i + 1], &arr[high]);


return i + 1;
}

// Quick Sort function


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

int main() {
int n;
printf("Enter number of elements (n > 5000 recommended):
");
scanf("%d", &n);

Dept. of AI&ML, SJCIT 23


int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Generate random numbers


for (int i = 0; i < n; i++) {
arr[i] = rand() % 10000;
}

// Measure time before sorting


clock_t start = clock();

// Call Quick Sort


quickSort(arr, 0, n - 1);

// Measure time after sorting


clock_t end = clock();

double time_taken = (double)(end - start) /


CLOCKS_PER_SEC;
printf("Time taken to sort %d elements using Quick Sort:
%.5f seconds\n", n, time_taken);

free(arr);
return 0;
}

Output

Sample 1:

Enter number of elements (n > 5000 recommended): 5500


Time taken to sort 5500 elements using Quick Sort: 0.00107
seconds
Program ended with exit code: 0

Sample 2:

Enter number of elements (n > 5000 recommended): 12000


Time taken to sort 12000 elements using Quick Sort: 0.00253
seconds
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 24


Sample 3:
Enter number of elements (n > 5000 recommended): 20000
Time taken to sort 20000 elements using Quick Sort: 0.00430
seconds
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 25


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>

// Merge two halves


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

// Create temp arrays


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

// Copy data to temp arrays


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

// Merge the temp arrays


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

while (i < n1 && j < n2) {


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

// Copy remaining elements


while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];

// Free temporary arrays


free(L);
free(R);
}

Dept. of AI&ML, SJCIT 26


// Merge Sort function
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);


}
}

int main() {
int n;
printf("Enter number of elements (n > 5000 recommended):
");
scanf("%d", &n);

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


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Generate random numbers


for (int i = 0; i < n; i++)
arr[i] = rand() % 10000;

clock_t start = clock();


mergeSort(arr, 0, n - 1);
clock_t end = clock();

double time_taken = (double)(end - start) /


CLOCKS_PER_SEC;
printf("Time taken to sort %d elements using Merge Sort:
%.5f seconds\n", n, time_taken);

free(arr);
return 0;
}

Dept. of AI&ML, SJCIT 27


Output

Sample 1:
Enter number of elements (n > 5000 recommended): 5800
Time taken to sort 5800 elements using Merge Sort: 0.00210
seconds
Program ended with exit code: 0

Sample 2:
Enter number of elements (n > 5000 recommended): 14000
Time taken to sort 14000 elements using Merge Sort: 0.00547
seconds
Program ended with exit code: 0

Sample 3:
Enter number of elements (n > 5000 recommended): 21000
Time taken to sort 21000 elements using Merge Sort: 0.00805
seconds
Program ended with exit code: 0

Dept. of AI&ML, SJCIT 28


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

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

#define MAX 20

int board[MAX];
int solutionCount = 0;

// Check if it's safe to place a queen at board[row][col]


bool isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i] == col || abs(board[i] - col) == abs(i -
row)) {
return false;
}
}
return true;
}

// Recursive function to solve the N-Queens problem


void solveNQueens(int row, int n) {
if (row == n) {
// A complete solution is found
solutionCount++;
printf("Solution %d:\n", solutionCount);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i] == j)
printf(" Q ");
else
printf(" . ");
}
printf("\n");
}
printf("\n");
return;
}

// Try placing queen in all columns of current row


for (int col = 0; col < n; col++) {
if (isSafe(row, col)) {
board[row] = col;
solveNQueens(row + 1, n);
}
}

Dept. of AI&ML, SJCIT 29


}

int main() {
int n;
printf("Enter the number of queens (N <= 15 recommended):
");
scanf("%d", &n);

if (n <= 0 || n > MAX) {


printf("Invalid value of N. Try N between 1 and %d.
\n", MAX);
return 1;
}

solveNQueens(0, n);
printf("Total solutions for N = %d: %d\n", n,
solutionCount);

return 0;
}

Output

Sample 1:
Enter the number of queens (N <= 15 recommended): 4
Solution 1:
. Q . .
. . . Q
Q . . .
. . Q .

Solution 2:
. . Q .
Q . . .
. . . Q
. Q . .

Total solutions for N = 4: 2


Program ended with exit code: 0

Sample 2:
Enter the number of queens (N <= 15 recommended): 25
Invalid value of N. Try N between 1 and 20.
Program ended with exit code: 1

Dept. of AI&ML, SJCIT 30


Viva Questions & Answers

1. What is Kruskal’s algorithm used for?


To find a Minimum Cost Spanning Tree in a connected, undirected graph.
2. How does Kruskal’s algorithm avoid cycles?
By using a Union-Find (Disjoint Set) structure to check and merge sets.
3. What is the primary difference between Prim’s and Kruskal’s algorithm?
Prim’s builds the MST by growing from a single vertex; Kruskal’s picks edges
globally.
4. What data structure is commonly used in Prim's algorithm?
A priority queue or min-heap for selecting the minimum edge.
5. What is the input format for Kruskal’s algorithm?
A list of edges with weights for an undirected connected graph.
6. What is the output of Prim’s or Kruskal’s algorithm?
A tree that connects all vertices with the minimum total edge weight.
7. What problem does Floyd’s algorithm solve?
It finds shortest paths between all pairs of vertices in a weighted graph.
8. What is the Warshall’s algorithm used for?
To find transitive closure of a directed graph using adjacency matrix.
9. What is the time complexity of Floyd's algorithm?
O(n³), where n is the number of vertices.
10. What is transitive closure?
It shows whether there is a path from vertex i to vertex j for all pairs (i, j).
11. What type of graphs does Dijkstra's algorithm work on?
Weighted graphs with non-negative edge weights.
12. What is the basic idea of Dijkstra’s algorithm?
It finds the shortest path from a source node to all other nodes using greedy
approach.
13. How does Dijkstra’s algorithm differ from Bellman-Ford?
Dijkstra is faster but does not handle negative weights; Bellman-Ford does.
14. What is a priority queue used for in Dijkstra's algorithm?
To always pick the node with the smallest tentative distance.
15. What kind of graph is needed for topological sorting?
A Directed Acyclic Graph (DAG).
16. What is the use of topological sorting?
It is used for scheduling tasks, like course prerequisites or job scheduling.

Dept. of AI&ML, SJCIT 31


17. Which algorithm is used for topological sorting?
DFS-based algorithm or Kahn's algorithm using in-degree.
18. What is 0/1 Knapsack problem?
Select items to maximize profit without exceeding capacity; items can’t be
broken.
19. Why use dynamic programming for 0/1 Knapsack?
It solves overlapping subproblems using a bottom-up approach with a table.
20. What is the time complexity of 0/1 Knapsack using DP?
O(nW), where n is the number of items and W is the capacity.
21. How is Greedy Knapsack different from 0/1 Knapsack?
Greedy allows taking fractional items (in fractional version), unlike 0/1.
22. Which Knapsack variant does greedy work optimally for?
Fractional Knapsack — sorts items by value/weight ratio.
23. Can greedy solve the 0/1 Knapsack optimally?
No, greedy does not guarantee the optimal solution for 0/1 Knapsack.
24. What is the Subset Sum problem?
To find if a subset of given integers sums up to a target value.
25. Which algorithmic technique is best for subset sum?
Backtracking or Dynamic Programming for efficient solution.
26. Is Subset Sum an NP-complete problem?
Yes, it belongs to the class of NP-complete problems.
27. How does Selection Sort work?
Repeatedly selects the smallest element and moves it to the sorted part.
28. What is the time complexity of Selection Sort?
O(n²) for all cases – best, average, and worst.
29. Is Selection Sort stable?
No, it is not a stable sort.
30. What is the space complexity of Selection Sort?
O(1) as it is an in-place sorting algorithm.
31. What is the basic idea of Quick Sort?
It uses divide and conquer to partition array and sort recursively.
32. What is the worst-case time complexity of Quick Sort?
O(n²), but on average it performs at O(n log n).
33. Is Quick Sort in-place?
Yes, it uses constant extra space for sorting.
34. How does Merge Sort work?
It divides the array into halves, recursively sorts, then merges.

Dept. of AI&ML, SJCIT 32


35. What is the space complexity of Merge Sort?
O(n) due to auxiliary space used during merging.
36. Is Merge Sort stable?
Yes, it preserves the relative order of equal elements.
37. What is the goal of the N-Queens problem?
To place N queens on an N×N board so that no two attack each other.
38. Which algorithm is used for solving N-Queens?
Backtracking is typically used to explore valid queen placements.
39. What are constraints in the N-Queens problem?
No two queens share the same row, column, or diagonal.
40. What is backtracking?
A problem-solving algorithm that builds solutions incrementally and abandons
them if they fail.
41. What is the difference between greedy and dynamic programming?
Greedy makes locally optimal choices; DP considers all subproblems.
42. Why do we analyze time complexity?
To predict performance and scalability of algorithms.
43. What is a spanning tree?
A subgraph that includes all vertices with the minimum number of edges and
no cycles.
44. What is the benefit of using a graph adjacency matrix?
Easy to implement and good for dense graphs.
45. What is the benefit of adjacency list over matrix?
Space efficient and faster for sparse graphs.
46. What is the divide and conquer approach?
Divide the problem, solve subproblems, and combine solutions.
47. How do you measure empirical time complexity?
By timing the algorithm on different input sizes and plotting the results.
48. What is memoization in dynamic programming?
It stores results of expensive function calls to avoid recalculations.
49. What are greedy algorithms good for?
Problems where local optimum choices lead to global optimum, like Fractional
Knapsack.
50. Why is algorithm design important?
Efficient algorithms save time, memory, and are crucial for solving real-world
problems.

***********************

Dept. of AI&ML, SJCIT 33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy