Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Analysis and design of algorithm lab

The document is a lab manual for the Analysis and Design of Algorithms course (BCSL404) at Dr. T. Thimmaiah Institute of Technology, detailing course objectives, outcomes, and evaluation methods. It outlines practical experiments for students, including algorithms like Kruskal's and Prim's for finding Minimum Cost Spanning Trees, as well as various sorting and optimization problems. The manual also includes information on the college's vision and mission, along with program outcomes expected from students upon completion of the B.E program.

Uploaded by

lekha DRTTIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Analysis and design of algorithm lab

The document is a lab manual for the Analysis and Design of Algorithms course (BCSL404) at Dr. T. Thimmaiah Institute of Technology, detailing course objectives, outcomes, and evaluation methods. It outlines practical experiments for students, including algorithms like Kruskal's and Prim's for finding Minimum Cost Spanning Trees, as well as various sorting and optimization problems. The manual also includes information on the college's vision and mission, along with program outcomes expected from students upon completion of the B.E program.

Uploaded by

lekha DRTTIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Dr. T.

THIMMAIAH INSTITUTE OF TECHNOLOGY


(Estd.1986) Oorgaum, Kolar Gold Fields, Karnataka–563120
(Affiliated to Visvesvaraya Technological University)
NAAC Accredited 'A' Grade

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

IV Semester
ANALYSIS AND DESIGN OF ALGORITHM (BSCL404)

LAB MANUAL

Name of the Student

USN of the Student


Dr. T.THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka – 563120
(AffiliatedtoVTU,Belgaum,ApprovedbyAICTE -NewDelhi)
NAAC Accredited 'A' Grade

Department of Computer Science and Engineering


Analysis & Design of Algorithms (BCSL404)

Name of the Student: _________________________

USN of the Student: ________________________


Dr. T.THIMMAIAH INSTITUTE OF TECHNOLOGY
(Estd. 1986) Oorgaum, Kolar Gold Fields, Karnataka –
563120
(AffiliatedtoVTU,Belgaum,ApprovedbyAICTE -NewDelhi)
NAAC Accredited 'A' Grade

Laboratory
Certificate
This is to certify that ……………………………………………………..bearing
USN ……………………….. has satisfactorily completed the experiments in
practical ANALYSIS AND DESIGN OF ALGORITHM prescribed by the
Visvesvaraya Technological University for the course with course code
BCSL404 in the Laboratory of this college in the year 2023-24.

Signature of the faculty in-charge Head of the Department

Final Marks obtained.


College Vision and Mission

College Vision:
To produce technically competent engineers having innovative skills, positive attitude, leadership and
professional ethics, with a focus on developing sustainable and new technology

College Mission:
● Create a conducive environment for teaching, learning and innovation by providing state of the
art infrastructure.
● Learnsustainableandnewtechnologiesthroughindustryinstitutecollaborations.
● Produce technically competent engineers with ethics, discipline and social consciousness through
holistic education.

Department of CSE Vision and Mission

Vision :
To produce highly competent and innovative Computer Science professionals through excellence in
teaching, training and research.

Mission :

 To provide appropriate infrastructure to impart need-based technical education through effective


teaching and research.
 To involve the students in innovative projects on emerging technologies to fulfill the industrial
requirements.
 To render leadership skills and ethical responsibilities in students that leads them to become
globally competent professionals.

.
BE: Program Outcomes (POs)
At the end of the B.E program, students are expected to have developed the following outcomes.

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, research literature, and analyse complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of need for
sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one‘s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE LEARNING OBJECTIVES AND OUTCOMES

Course Objectives:

This course will enable students to:

CL To design and implement various algorithms in C/C++ programming using suitable development
O1 tools to address different computational challenges
CL
To apply diverse design strategies for effective problem-solving.
O2
CL To Measure and compare the performance of different algorithms to determine their efficiency and
O3 suitability for specific tasks.

Course Outcomes:

At the end of the course the student will be able to:

CO1 Develop programs to solve computational problems using suitable algorithm design strategy.

Compare algorithm design strategies by developing equivalent programs and observing running
CO2
times for analysis.
Conduction of Practical Examination:

Assessment Details (both CIE and SEE)

⮚ The weightage of Continuous Internal Evaluation (CIE) is50% 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).
⮚ The minimum passing mark for the SEE is 35% of the maximum marks (18 marks out of 50).
⮚ A student shall be deemed to have satisfied the academic requirements and earned the credits
allotted to each subject/course if the students secures not less than 35% (18Marks out of 50) in
the semester-end examination (SEE), and 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..
● 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 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.
Lab Participation Rubric (Conduction)
Proficient(20-18) Good(17- Adequate(13- Substandard(8- Unacceptable(3-
14) 9) 4) 0)
Lab Lab Lab Lab performance Lab performance
performance is performance is performance is fair. is barely
excellent. good. At most, is adequate. The student adequate.
The student has the student has The student is may have been The
attended all labs. one lab absent more absent 3-4 student is
Student absence. than 2 classes. times. irregular.
demonstrates an Student Student Student Student was late
accurate demonstrates a arrives on unpreparedness to lab or did not
understanding of fair time to lab, makes it participate.
the lab objectives understanding but may be impossible to There was no
and concepts. The of the lab unprepared. fully participate. attempt to make
student can objectives and Answers to If able to prior
correctly answer concepts. questions are participate, arrangements to
questions and if The student basic and student has make up the lab.
appropriate, can can answer superficial difficulty
explain concepts questions suggesting explaining key
to fellow that concepts lab concepts.
classmates. are not fully
Student is eager grasped
to participate and
assists when
needed.
Dr. T.THIMMAIAHINSTITUTEOFTECHNOLOGY
Department of Computer Science and Engineering
Analysis and Design of Algorithm Lab
BCSL404

Contents

Ex Page
Title of the Experiment
p.
No
N
o
1
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 2
connected undirected graph using Prim's algorithm
.
a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
3. Floyd's algorithm. 3
b. Design and implement C/C++ Program to find the transitive closure using Warshal's
algorithm
Design and implement C/C++ Program to find shortest paths from a given vertex in a
4. 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
5. given digraph. 7
Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
6. Programming method. 8
Design and implement C/C++ Program to solve discrete Knapsack and continuous
7. Knapsack problems using greedy approximation method. 9
Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn}
8. of n positive integers whose sum is equal to a given positive integer d. 10
9. Design and implement C/C++ Program to sort a given set of n integer elements using 11
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 12
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 3
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 15
EVALVUATION SHEET

S
l Date of Date of Faculty
Conducti Reco
. Conducti TITLEOFTHEEXPERIMENT Submissio Sign with
on rd
N on n Date
o

Minimum Cost Spanning Tree using


1 Kruskal's algorithm

2 Minimum Cost Spanning Tree using Prim's


algorithm
All-Pairs Shortest Paths problem using
3a Floyd's algorithm.

Transitive closure using Warshal's algorithm


3b
Shortest path using Dijkstra's algorithm.
4
Topological ordering of vertices in a given
5 digraph.
0/1 Knapsack problem using Dynamic
6 Programming method.
Discrete Knapsack and continuous Knapsack
7 problems using greedy approximation
method.
To find a subset of a given set S = {sl ,
8 s2,.....,sn} of n positive integers whose sum
is equal t
Sort a given set of n integer elements using
9 Selection Sort method
Sort a given set of n integer elements using
10 Quick Sort method
Sort a given set of n integer elements using
11 Merge Sort
12 N Queen's problem using Backtracking

Conducti Record Average Test Marks Total Signature of the faculty


on marks with Date
marks
Analysis & Design of Algorithms Lab [BSCL404] 2023-24

1) Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
given connected undirected graph using Kruskal's algorithm
In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on
adding new edges and nodes in the MST if the newly added edge does not form a cycle. It picks
the minimum weighted edge at first and the maximum weighted edge at last. Thus we can say
that it makes a locally optimal choice in each step in order to find the optimal solution. Hence
this is a Greedy Algorithm.
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the
cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

ALGORITHM Kruskal(G)
//Kruskal’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = V,E
//Output: ET , the set of edges composing a minimum spanning tree of G

ET ← ∅; ecounter ← 0
sort E in nondecreasing order of the edge weights w(ei1 ) ≤ ... ≤ w(ei|E| )
//initialize the set of tree edges and its size
k←0 //initialize the number of processed edges
whileecounter< |V | − 1 do

if ET ∪ {eik } is acyclic
k←k+1

ET ← ET ∪ {eik }; ecounter ← ecounter + 1


return ET

Dept.of CSE,Dr. TTIT,KGF Page1


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

2. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a
given connected undirected graph using Prim's algorithm.
Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node
and moves through several adjacent nodes, in order to explore all of the connected edges along
the way.
The algorithm starts with an empty spanning tree. The idea is to maintain two sets of vertices.
The first set contains the vertices already included in the MST, and the other set contains the
vertices not yet included. At every step, it considers all the edges that connect the two sets and
picks the minimum weight edge from these edges. After picking the edge, it moves the other
endpoint of the edge to the set containing MST.
A group of edges that connects two sets of vertices in a graph is called cut in graph theory. So,
at every step of Prim’s algorithm, find a cut, pick the minimum weight edge from the cut, and
include this vertex in MST Set (the set that contains already included vertices).

The working of Prim’s algorithm can be described by using the following steps:
Step 1: Determine an arbitrary vertex as the starting vertex of the MST.
Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as
fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

ALGORITHMPrim(G) //Prim’s algorithm for constructing a minimum spanning tree


//Input: A weighted connected graph G =V,E
//Output: ET , the set of edges composing a minimum spanning tree of G

ET ← ∅
VT ← {v0} //the set of tree vertices can be initialized with any vertex

fori ← 1 to |V | − 1 do
find a minimum-weight edge e∗ = (v∗, u∗) among all the edges (v, u)

VT ← VT ∪ {u∗}
such that v is in VT and u is in V − VT

ET ← ET ∪ {e∗}
return ET

Dept.of CSE,Dr. TTIT,KGF Page2


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

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

The Floyds algorithm is a graph algorithm that is deployed to find the shortest path between
all the vertices present in a weighted graph. This algorithm is different from other shortest path
algorithms; to describe it simply, this algorithm uses each vertex in the graph as a pivot to
check if it provides the shortest way to travel from one point to another.
Consider a graph, G = {V, E} where V is the set of all vertices present in the graph and E is the
set of all the edges in the graph. The graph, G, is represented in the form of an adjacency
matrix, A, that contains all the weights of every edge connecting two vertices.
Step 1 − Construct an adjacency matrix A with all the costs of edges present in the graph. If
there is no path between two vertices, mark the value as ∞.
Step 2 − Derive another adjacency matrix A1 from A keeping the first row and first column of
the original adjacency matrix intact in A1. And for the remaining values, say A1[i,j],
if A[i,j]>A[i,k]+A[k,j] then replace A1[i,j] with A[i,k]+A[k,j]. Otherwise, do not change the
values. Here, in this step, k = 1 (first vertex acting as pivot).
Step 3 − Repeat Step 2 for all the vertices in the graph by changing the k value for every pivot
vertex until the final matrix is achieved.
Step 4 − The final adjacency matrix obtained is the final solution with all the shortest paths.

ALGORITHMFloyd(W[1..n, 1..n])
//Implements Floyd’s algorithm for the all-pairs shortest-paths problem
//Input: The weight matrix W of a graph with no negative-length cycle
//Output: The distance matrix of the shortest paths’ lengths
D←W //is not necessary if W can be overwritten
for k ← 1 to n do
fori ← 1 to n do
for j ← 1 to n do
D[i, j ] ← min{D[i, j ], D[i, k] + D[k, j ]}
return D

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

Warshall's algorithm is used to determine the transitive closure of a directed graph or all paths
in a directed graph by using the adjacency matrix. For this, it generates a sequence of n

Dept.of CSE,Dr. TTIT,KGF Page3


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

matrices. Where, n is used to describe the number of vertices.

R(0), ..., R(k-1), R(k), ... , R(n)

A sequence of vertices is used to define a path in a simple graph. In the kth matrix (R(k)),
(rij(k)), the element's definition at the ith row and jth column will be one if it contains a path
from vi to vj. For all intermediate vertices, wq is among the first k vertices that mean 1 ≤ q ≤ k.

The R(0) matrix is used to describe the path without any intermediate vertices. So we can say
that it is an adjacency matrix. The R(n) matrix will contain ones if it contains a path between
vertices with intermediate vertices from any of the n vertices of a graph. So we can say that it is
a transitive closure.

Now we will assume a case in which r ij(k) is 1 and rij(k-1) is 0. This condition will be true only if it
contains a path from vi to vj using the vk. More specifically, the list of vertices is in the
following form

vi, wq (where 1 ≤ q < k), vk. wq (where 1 ≤ q < k), vj

So in summary, we can say that rij(k) = rij(k-1) or (rik(k-1) and rkj(k-1))

ALGORITHM Warshall(A[1..n, 1..n])


//Implements Warshall’s algorithm for computing the transitive closure
//Input: The adjacency matrix A of a digraph with n vertices
//Output: The transitive closure of the digraph
R(0) ← A
for k ← 1 to n do
fori ← 1 to n do
for j ← 1 to n do
R(k)[i, j ] ← R(k−1)[i, j ] or (R(k−1)[i, k] and R(k−1)[k, j ])
return R(n)

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.

Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a
weighted graph.

Dept.of CSE,Dr. TTIT,KGF Page4


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

Let the node at which we are starting be called the starting node. Let the distance of node N be
the distance from the starting node to N. Dijkstra's algorithm will initially start with infinite
distances and will try to improve them step by step.

1. Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set.
2. Assign to every node a distance from start value: set it to zero for our starting node and
to infinity for all other nodes. During the run of the algorithm, the distance of a
node N is the length of the shortest path discovered so far between the node N and
the starting node. Since initially no path is known to any other node than the starting
node (which is a path of length zero), all other distances are initially set to infinity. Set
the starting node as current.[17]
3. For the current node, consider all of its unvisited neighbours and update their distances
through the current node: Compare the newly calculated distance to the one currently
assigned to the neighbour and assign it the smaller one. For example, if the current
node A is marked with a distance of 6, and the edge connecting it with its
neighbour B has length 2, then the distance to B through A is 6 + 2 = 8. If B was
previously marked with a distance greater than 8 then change it to 8 (the path to B
through A is shorter). Otherwise, keep its current distance (the path to B through A is
not the shortest).
4. When we are done considering all of the unvisited neighbours of the current node, mark
the current node as visited and remove it from the unvisited set. A visited node will
never be checked again. At this point, this visited node recorded distance is final and
minimal because this node was selected to be the next to visit due to having the
smallest distance from the starting node, cf. next step.
5. Review the unvisited nodes and select the one with the smallest known distance as the
new "current node" and go back to step 3. If an unvisited node has an "infinity"
distance, it means that it's not reachable (so far) and should not be selected. If there are
no more reachable unvisited nodes, the algorithm has finished. If the new "current
node" is the target node, it means we found a possible path to it, but not necessarily the
shortest (we can't know before visiting all nodes). Depending on the application, it's
possible to early exit here if the shortest path is not required or if we have ways to
know it's the shortest path.
Once the loop exited, the shortest path can be extracted from the set of visited nodes by starting
from the target node and picking its neighbour with the shortest distance, going back to start on
an optimal path. If the target node recorded distance is infinite, it means no path exists.

ALGORITHM Dijkstra(G, s)
//Dijkstra’s algorithm for single-source shortest paths
//Input: A weighted connected graph G = V,E with nonnegative weights and its vertex s
//Output: The length dv of a shortest path from s to v and its penultimate vertex pv for every

Dept.of CSE,Dr. TTIT,KGF Page5


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

vertex v in V
Initialize (Q) //initialize priority queue to empty
for every vertex v in V
dv ← ∞; pv ← null
Insert(Q, v, dv) //initialize vertex priority in the priority queue

VT ← ∅
ds ← 0; Decrease(Q, s, ds) //update priority of s with ds

fori ← 0 to |V | − 1 do

VT ← VT ∪ {u∗}
u∗ ← DeleteMin(Q) //delete the minimum priority element

for every vertex u in V − VT that is adjacent to u∗ do


if du∗ + w(u∗, u) < du
du ← du∗ + w(u∗, u); pu ← u∗
Decrease(Q, u, du)

Dept.of CSE,Dr. TTIT,KGF Page6


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

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

A topological sort is a linear ordering of vertices in a directed acyclic graph (DAG).


Given a DAG G = (V, E), a topological sort algorithm returns a sequence of vertices in

(u, v) ∈ E, v never appears before u in the sequence. A topological sort of a graph can be
which the vertices never come before their predecessors on any paths. In other words, if

represented as a horizontal line of ordered vertices, such that all edges point only to the
right

ALGORITHMDFS(G)
//Implements a depth-first search traversal of a given graph
//Input: Graph G = V,E
//Output: Graph G with its vertices marked with consecutive integers
// in the order they are first encountered by the DFS traversal

mark each vertex in V with 0 as a mark of being “unvisited”


count ← 0
for each vertex v in V do
if v is marked with 0
dfs(v)
count ← count + 1; mark v with count
for each vertex w in V adjacent to v do
if w is marked with 0
dfs(w)

Dept.of CSE,Dr. TTIT,KGF Page7


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

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

Given N items where each item has some weight and profit associated with it and also given a
bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items
into the bag such that the sum of profits associated with them is the maximum possible.

Given N items where each item has some weight and profit associated with it and also given a
bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items
into the bag such that the sum of profits associated with them is the maximum possible.

Input: N = 3, W = 4, profit[] = {1, 2, 3}, weight[] = {4, 5, 1}


Output: 3

Explanation: There are two items which have weight less than or equal to 4. If we select the
item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible
profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with
weight 4 and 1 together as the capacity of the bag is 4.
A simple solution is to consider all subsets of items and calculate the total weight and profit of
all subsets. Consider the only subsets whose total weight is smaller than W. From all such
subsets, pick the subset with maximum profit.
Optimal Substructure: To consider all subsets of items, there can be two cases for every item.
 Case 1: The item is included in the optimal subset.
 Case 2: The item is not included in the optimal set.

ALGORITHMMFKnapsack(i, j )
//Implements the memory function method for the knapsack problem
//Input: A nonnegative integer i indicating the number of the first items being considered and a
nonnegative integer j indicating the knapsack capacity
//Output: The value of an optimal feasible subset of the first i items
//Note: Uses as global variables input arrays W eights[1..n], V alues[1..n], and table F[0..n,
0..W] whose entries are initialized with −1’s except for row 0 and column 0 initialized with 0’s
if F[i, j ] < 0
if j < Weights[i]
value ← MFKnapsack(i − 1, j)
else
value ← max(MFKnapsack(i − 1, j ),
Values[i] + MFKnapsack(i − 1, j − Weights[i]))

F[i, j ]← value
return F[i, j ]

Dept.of CSE,Dr. TTIT,KGF Page8


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

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

Method:
The Knapsack’s filling is done so that the maximum capacity of the knapsack is utilized
so that maximum profit can be earned from it. The knapsack problem using the Greedy
Method is referred to as:
Given a list of n objects, say {I1, I2,……, In) and a knapsack (or bag).
The capacity of the knapsack is M.

If a fraction xj (where x ∈ {0…, 1)) of an object Ij is placed into a knapsack, then a profit
Each object Ij has a weight wj and a profit of pj

of pjxj is earned.
The problem (or Objective) is to fill the knapsack (up to its maximum capacity M),
maximizing the total profit earned.

Algorithm
Steps:
1. Note that the value of xj will be any value between 0 and 1 (inclusive).
2. If any object Ij is completely placed into a knapsack, its value is 1 (xj = 1).
3. If we do not pick (or select) that object to fill into a knapsack, its value is 0 ( xj = 0).
4. Otherwise, if we take a fraction of any object, then its value will be any value between 0 & 1

Dept.of CSE,Dr. TTIT,KGF Page9


Analysis & Design of Algorithms Lab [BSCL404] 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
In the sum of subsets problem, there is a given set with some non-negative integer
elements. And another sum value is also provided, our task is to find all possible subsets of
the given set whose sum is the same as the given sum value
Suppose the given set and sum value is −
Set = {1, 9, 7, 5, 18, 12, 20, 15}
sum value = 35
All possible subsets of the given set, where sum of each element for every subset is the
same as the given sum value are given below −
{1 9 7 18}
{1 9 5 20}
{5 18 12}

ALGORITHM Backtrack(X[1..i])
//Gives a template of a generic backtracking algorithm
//Input: X[1..i] specifies first i promising components of a solution
//Output: All the tuples representing the problem’s solutions

if X[1..i] is a solution write X[1..i]

for each element x ∈ Si+1 consistent with X[1..i] and the constraints do
else

X[i + 1]← x
Backtrack(X[1..i + 1])

Dept.of CSE,Dr. TTIT,KGF Page10


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

9. Design and implement C/C++ Program to sort a given set of n integer elements using
SelectionSort method and compute its time complexity. Run the program for varied
values of n> 5000and record the time taken to sort. Plot a graph of the time taken versus
n. The elements can bereadfrom a file or can be generated using the random number
generator

Selection Sort
1. In the selection sort, first of all, we set the initial element as a minimum.
2. Now we will compare the minimum with the second element. If the second element turns out
to be smaller than the minimum, we will swap them, followed by assigning to a minimum to
the third element.
3. Else if the second element is greater than the minimum, which is our first element, then we
will do nothing and move on to the third element and then compare it with the minimum.
4. We will repeat this process until we reach the last element.
5. After the completion of each iteration, we will notice that our minimum has reached the start
of the unsorted list.
6. For each iteration, we will start the indexing from the first element of the unsorted list. We
will repeat the Steps from 1 to 4 until the list gets sorted or all the elements get correctly
positioned.

ALGORITHM SelectionSort(A[0..n − 1])


//Sorts a given array by selection sort
//Input: An array A[0..n − 1] of orderable elements
//Output: Array A[0..n − 1] sorted in nondecreasing order
fori ← 0 to n − 2 do
min ← i
for j ← i + 1 to n − 1 do
if A[j ] < A[min] min ← j
swap A[i] and A[min]

Dept.of CSE,Dr. TTIT,KGF Page11


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

10. Design and implement C/C++ Program to sort a given set of n integer elements using
Quick Sortmethod and compute its time complexity. Run the program for varied values
of n> 5000 andrecord the time taken to sort. Plot a graph of the time taken versus n. The
elements can be readfrom a file or can be generated using the random number generator.
Quick Sort
Quicksort is a type of divide-and-conquer algorithm for sorting an array, based on a partitioning
routine; Partitioning produces a division into two consecutive non empty sub-ranges, in such a
way that no element of the first sub-range is greater than any element of the second sub-range.
After applying this partition, quicksort then recursively sorts the sub-ranges
If the range has fewer than two elements, return immediately as there is nothing to do.

1. Pick a value, called a pivot that occurs in the range


2. Partition the range: reorder its elements, while determining a point of division, so that
all elements with values less than the pivot come before the division, while all elements
with values greater than the pivot come after it; elements that are equal to the pivot can
go either way. Since at least one instance of the pivot is present, most partition routines
ensure that the value that ends up at the point of division is equal to the pivot, and is
now in its final position
3. Recursively apply the quicksort to the sub-range up to the point of division and to the
sub-range after it, possibly excluding from both ranges the element equal to the pivot at
the point of division.

ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r
//Output: SubarrayA[l..r] sorted in nondecreasing order
if l<r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s − 1])
Quicksort(A[s + 1..r])

ALGORITHM HoarePartition(A[l..r])
//Partitions a subarray by Hoare’s algorithm, using the first element as a pivot
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value

p ← A[l]
i ← l; j ← r + 1
repeat
repeati ← i + 1 until A[i] ≥ p
repeat j ← j − 1 until A[j ] ≤ p

Dept.of CSE,Dr. TTIT,KGF Page12


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

swap(A[i], A[j ])
untili ≥ j
swap(A[i], A[j ]) //undo last swap when i ≥ j
swap(A[l], A[j ])
return j

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 bereadfrom a file or can be generated using the random number generator.

Merge Sort

• Merge sort is yet another sorting algorithm that falls under the category of Divide and
Conquer technique.

• It is one of the best sorting techniques that successfully build a recursive algorithm.

Step-1: The merge sort algorithm iteratively divides an array into equal halves until we achieve
an atomic value. In case if there are an odd number of elements in an array, then one of the
halves will have more elements than the other half.

Step-2: After dividing an array into two sub arrays, we will notice that it did not hamper the
order of elements as they were in the original array. After now, we will further divide these two
arrays into other halves.

Step-3: Again, we will divide these arrays until we achieve an atomic value, i.e., a value that
cannot be further divided.

Step-4: Next, we will merge them back in the same way as they were broken down.

Step-5: For each list, we will first compare the element and then combine them to form a new
sorted list.

Step-6: In the next iteration, we will compare the lists of two data values and merge them back
into a list of found data values, all placed in a sorted manner.

ALGORITHMMergesort(A[0..n − 1])
//Sorts array A[0..n − 1] by recursive mergesort
//Input: An array A[0..n − 1] of orderable elements
//Output: Array A[0..n − 1] sorted in nondecreasing order

Dept.of CSE,Dr. TTIT,KGF Page13


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

if n > 1
copy A[0..n/2 − 1] to B[0..n/2 − 1]
copy A[n/2..n − 1] to C[0..n/2 − 1]
Mergesort(B[0..n/2 − 1])
Mergesort(C[0..n/2 − 1])
Merge(B, C, A)

ALGORITHM Merge(B[0..p − 1], C[0..q − 1], A[0..p + q − 1])


//Merges two sorted arrays into one sorted array
//Input: Arrays B[0..p − 1] and C[0..q − 1] both sorted
//Output: Sorted array A[0..p + q − 1] of the elements of B and C
i ← 0; j ← 0; k ← 0
whilei<p and j<q do
if B[i] ≤ C[j ]
A[k]← B[i]; i ← i + 1
else A[k]← C[j ]; j ← j + 1
k←k+1
ifi = p
copy C[j..q − 1] to A[k..p + q − 1]
else copy B[i..p − 1] to A[k..p + q − 1]

Dept.of CSE,Dr. TTIT,KGF Page14


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

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

The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this row
and column as part of the solution. If we do not find such a row due to clashes, then we
backtrack and return false.

Steps
 Start in the leftmost column
 If all queens are placed return true
 Try all rows in the current column. Do the following for every row.
If the queen can be placed safely in this row
 Then mark this [row, column] as part of the solution and recursively
check if placing queen here leads to a solution.
 If placing the queen in [row, column] leads to a solution then
return true.
 If placing queen doesn’t lead to a solution then unmark this [row,
column] then backtrack and try other rows.
If all rows have been tried and valid solution is not found return false to trigger
backtracking.

ALGORITHM Backtrack(X[1..i])
//Gives a template of a generic backtracking algorithm
//Input: X[1..i] specifies first i promising components of a solution
//Output: All the tuples representing the problem’s solutions

if X[1..i] is a solution write X[1..i]

for each element x ∈ Si+1 consistent with X[1..i] and the constraints do
else

X[i + 1]← x
Backtrack(X[1..i + 1])

Dept.of CSE,Dr. TTIT,KGF Page15


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

Viva Questions and Answers

1) What is the time complexity of linear search? Θ(n)

2) What is the time complexity of binary search? Θ(log2n)

3) What is the major requirement for binary search? The given list should be sorted.

4) What is binary search?


It is an efficient method of finding out a required item from a given list, provided the list is in order. The
process is:
1. First the middle item of the sorted list is found.
2. Compare the item with this element.
3. If they are equal search is complete.
4. If the middle element is greater than the item being searched, this process is repeated in the upper half of
the list.
5. If the middle element is lesser than the item being searched, this process is repeated in the lower half of the
list.

5) What is parental dominance?


The key at each node is greater than or equal to the keys at its children.

6) What is heap?
A heap can be defined as a binary tree with keys assigned to its nodes (one key per node) provided the
following two conditions are met:
1 The tree’s shape requirement
The binary tree is essentially complete that is, all its levels are full except possibly the last level, where only some
rightmost leaves may be missing.
2. The parental dominance requirement
The key at each node is greater than or equal to the keys at its children.

17) What is the time complexity of Selection Sort algorithm? (n2)

18) Is Selection Sort Inplace? Yes.

19)Is Selection Sort stable? Yes.

20) Why is the name Selection Sort?


Algorithm selects the smallest number in the array and places it in its final position the sorted array.

21) When is Selection Sort algorithm useful?


Selection Sort algorithm is useful for small inputs because it requires comparisons .Selection Sort algorithm
requires (n-1) swaps & hence (n) memory writes. Thus it can be very useful if writes are the most expensive
operation.

22) What are the drawbacks of Selection Sort?


Inefficient on large lists. It requires same number of iterations no matter how well-organized the array is. It uses
internal sorting, means it would require the entire array to be in main memory.

Dept.of CSE,Dr. TTIT,KGF Page16


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

23) When is a problem said to have overlapping sub problems?


A problem is said to have overlapping sub problems if it can be broken down into sub problems which are
reused multiple times. This is closely related to recursion.

24) What is principle of optimality?


The optimal solution to any instance of an optimization problem is composed of optimal solutions to its sub
instances.

25) Can knapsack problem be solved in any other technique?


It can be solved using many other techniques such as Brute Force, Greedy technique, Branch and bound etc..

26) Mention few applications of dynamic programming.


Can be applied to find factorial, Fibonacci numbers in which the required value may depend on previously
computed values. To find the longest common substrings of the strings "ABAB", "BABA" and “ABBA" are the
strings "AB" and "BA" of length 2. Other common substrings are "A", "B" and the empty string “”. etc..

27) Compare Dynamic programming and Divide and conquer.


Dynamic programming differs from the "Divide and Conquer" (D-and-C) method in the fact that the problems
solved by D-and-C can have many non-overlapping sub problems - i.e, new sub problems may be generated
when the method is applied. Both use recursion.

28) Who invented Dijkstra’s Algorithm?


Edsger Dijkstra invented this algorithm.

29) What is the other name for Dijkstra’s Algorithm?


Single Source Shortest Path Algorithm.

30) Which technique the Dijkstra’s algorithm is based on?


Greedy Technique.

31) What is the purpose of Dijkstra’s Algorithm?


To find the shortest path from source vertex to all other remaining vertices

32) Name the different algorithms based on Greedy technique.


Prim’s Algorithm, Kruskal’s algorithm

33) What is the constraint on Dijkstra’s Algorithm?


This algorithm is applicable to graphs with non-negative weights only.

34) What is a Weighted Graph?


A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights or costs.

35) What is a Connected Graph?


A graph is said to be connected if for every pair of its vertices u and v there is a path from u to v.

36) What is the time complexity of Dijkstra’s algorithm?


For adjacency matrix, It is O(IVI*IVI)For adjacency list with edges stored as min heap, it is O(IEIlogIVI)

37) Differentiate b/w Traveling Salesman Problem (TSP) and Dijkstra’s Algorithm.
In TSP, given n cities with known distances b/w each pair, find the shortest tour that passes through all the cities
exactly once before returning to the starting city.

Dept.of CSE,Dr. TTIT,KGF Page17


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

In Dijkstra’s Algorithm, find the shortest path from source vertex to all other remaining vertices

38) Differentiate b/w Prim’s Algorithm and Dijkstra’s Algorithm?


Prim’s algorithm is to find minimum cost spanning tree.
Dijkstra’s algorithm is to find the shortest path from source vertex to all other remaining vertices.

39) What are the applications of Dijkstra’s Algorithm?


It finds its application even in our day to day life while travelling. They are helpful in routing applications.

40) Who was the inventor of the Quicksort?


C.A.R.HOARE, a British Scientist.

41) Which design strategy does Quicksort uses?


Divide and Conquer

42) What is Divide and Conquer Technique?


(I) divide the instance of a problem into two or more smaller instances (II) solve the smaller instances
recursively (III) Obtain solution to original instances by combining

43) What is the other name for Quicksort?


Partition Exchange Sort

44) What are the advantages and disadvantages?


Advantage: Fastest among all sorting algorithms Suitable when the input size is very large
Disadvantage: Heavily based on recursive sorting technique. It takes O (n* log n) time and O (log n)
additional space due to Recursion

45) Is Quicksort Stable as well as Inplace?


Not Stable but Inplace.

46) When do you say that a Quick sort having best case complexity?
When the pivot exactly divides the array into equal half

47) When do you say that Quick sort having worst case complexity?
When any one of the sub array is empty

48) How many more comparisons are needed for average case compared to best case?
38% more

49) When do you say that the pivot element is in its final position?
When all the elements towards the left of pivot are <= pivot and all theelements towards the right of pivot are >=
pivot.

50) What is CLK_TCK?


Macro defines the number of clock ticks per second which is available in the TIME. H header file.

51) What technique does kruskal’s algorithm follow?


greedy technique

52) What is the time complexity?


With an efficient sorting algorithm, the time efficiency of an kruskal’s algorithm will be in O(|E|log|E|).

Dept.of CSE,Dr. TTIT,KGF Page18


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

53) Who is the inventor of kruskal’s algorithm?


Joseph Kruskal.

54) Which technique is used to solve BFS & DFS problems?


Decrease and Conquer

55) What is BFS traversal?


It proceeds in a concentric manner by visiting first all the vertices that are adjacent to a starting vertex, then all
unvisited vertices two edges apart from it and so on, until all the vertices are in the same connected component as
the starting vertex are visited. If there still remains unvisited vertices, the algorithm to be restarted at an arbitrary
vertex of another connected component of a graph.

56) What is DFS traversal?


Consider an arbitrary vertex v and mark it as visited on each iteration, proceed to an unvisited vertex w adjacent
to v. we can explore this new vertex depending upon its adjacent information. This process continues until dead
end is encountered.(no adjacent unvisited vertex is available). At the dead end the algorithm backs up by one
edge and continues the process of visiting unvisited vertices. This process continues until we reach the starting
vertex.

57) What are Tree edge, Back edge & Cross edge? Tree edge:
Whenever a new unvisited vertex is reached for the first time, it is attached as a child to the vertex from which it
is being visited. Such an edge is called a tree edge.
Back edge: A
An edge leading to a previously visited vertex other than its immediate predecessor. Such an edge is called a
back edge
Cross edge
If an edge leading to a previously visited vertex other than its immediate predecessor (i.e. its parent in the tree). Is
encountered, the edge is noted as a cross edge.

58) What are the various applications of BFS & DFS tree traversal technique?
Application of BFS
Checking connectivity and checking acclivity of a graph. Check whether there is only one root in the BFS forest
or not. If there is only one root in the BFS forest, then it is connected graph otherwise disconnected graph. For
checking cycle presence, we can take advantage of the graph’s representation in the form of a BFS forest, if the
latter vertex does not have cross edge, then the graph is acyclic.
Application of DFS
To check whether given graph is connected or not. To check whether the graph is cyclic or not. To find
the spanning tree. Topological sorting.

59) Which data structures are used in BFS & DFS tree traversal technique?
We use Stack data structure to traverse the graph in DFS traversal. We use queue data structure to
traverse the graph in DFS traversal.

60) What are the efficiencies of BFS & DFS algorithms for Adjacency
matrix and adjacency list representation?
Adjacency matrices: Θ(V2)
Adjacency linked lists: Θ(V+E)

Dept.of CSE,Dr. TTIT,KGF Page19


Analysis & Design of Algorithms Lab [BSCL404] 2023-24

Dept.of CSE,Dr. TTIT,KGF Page20

You might also like