Analysis and design of algorithm lab
Analysis and design of algorithm lab
IV Semester
ANALYSIS AND DESIGN OF ALGORITHM (BSCL404)
LAB MANUAL
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.
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.
Vision :
To produce highly competent and innovative Computer Science professionals through excellence in
teaching, training and research.
Mission :
.
BE: Program Outcomes (POs)
At the end of the B.E program, students are expected to have developed the following outcomes.
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:
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:
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:
⮚ 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.
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
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
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
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
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
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
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.
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
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
5. Design and implement C/C++ Program to obtain the Topological ordering of vertices in
a given digraph
(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
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.
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 ]
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
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
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])
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.
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.
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
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
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)
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
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])
3) What is the major requirement for binary search? The given list should be sorted.
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.
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.
In Dijkstra’s Algorithm, find the shortest path from source vertex to all other remaining vertices
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.
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)