Design Analysis of Algorithms 14102024
Design Analysis of Algorithms 14102024
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LABORATORY MANUAL
B.Tech. Semester- V
DEPARTMENT OF CSE/CSIT/IT/IOT
DRONACHARYA COLLEGE OF ENGINEERING
KHENTAWAS, FARRUKH NAGAR, GURUGRAM (HARYANA)
1
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Table of Contents
1. Vision and Mission of the Institute
2. Vision and Mission of the Department
3. Programme Educational Objectives (PEOs)
4. Programme Outcomes (POs)
5. Programme Specific Outcomes (PSOs)
6. University Syllabus
7. Course Outcomes (COs)
8. CO- PO and CO-PSO mapping
9. Course Overview
10. List of Experiments
11. DOs and DON’Ts
12. General Safety Precautions
13. Guidelines for students for report preparation
14. Lab assessment criteria
15. Details of Conducted Experiments
16. Lab Experiments
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Vision:
“Empowering human values and advanced technical education to navigate and address global
Mission:
M1: Seamlessly integrate human values with advanced technical education.
M2: Supporting the cultivation of a new generation of innovators who are not only
M3: Inspire global citizens who are equipped to create positive and sustainable impact, driving
progress towards a more inclusive and harmonious world.
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Mission:
M1: Directing future innovations in computer science through revolutionary progress.
PEO1: Apply the technical competence in Computer Science and Engineering for solving
PEO2: Carry out research and develop solutions on problems of social applications.
PEO3: Work in a corporate environment, demonstrating team skills, work morals, flexibility
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PSO1: Exhibit design and programming skills to develop and mechanize business solutions
PSO2: Learn strong theoretical foundation leading to brilliance and enthusiasm towards
PSO3: Work effectively with diverse Engineering fields as a team to design, build and
PSO1: Exhibit design and programming skills to develop and mechanize business solutions
PSO2: Learn strong theoretical foundation leading to brilliance and enthusiasm towards
PSO3: Work effectively with diverse Engineering fields as a team to design, build and
University Syllabus
CO-PO Mapping
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C325.1 1 1 3 3 3 3 3 3 2 2 2
C325.2 1 1 3 3 3 3 2 2 1 1 2
C325.3 2 3 2 1 2 3 3 1 2
C325.4 2 3 3 1 1 2 2 1 1 2
CO-PSO Mapping
PSO1 PSO2 PSO3
C325.1 1 1 1
C325.2 2 1 2
C325.3 3 3 3
C325.4 1 1 1
Course Overview
The design and analysis of algorithms is a field within computer science that focuses on
developing efficient and effective algorithms for solving computational problems. It involves the
study of various techniques, methodologies, and mathematical tools to design algorithms,
analyze their performance, and evaluate their efficiency.
The process of designing an algorithm involves understanding the problem at hand, defining the
problem's requirements and constraints, and devising a step-by-step procedure to solve it. This
includes selecting appropriate data structures, determining the sequence of operations, and
considering algorithmic paradigms such as divide and conquer, greedy algorithms, dynamic
programming, and more.
Once an algorithm is designed, the next step is to analyze its performance. This involves
evaluating factors like time complexity (how the algorithm's running time increases with input
size), space complexity (how much memory the algorithm requires), and other relevant metrics.
By analyzing an algorithm's performance, we can determine its efficiency and scalability,
enabling us to make informed decisions about which algorithm to use for a given problem.
The goal of the design and analysis of algorithms is to develop algorithms that are correct,
efficient, and scalable. Correctness ensures that the algorithm produces the correct output for all
possible inputs. Efficiency focuses on minimizing the use of computational resources such as
time and memory. Scalability considers how well the algorithm performs as the input size
becomes larger.
By studying the design and analysis of algorithms, computer scientists can develop solutions that
are both practical and optimized, leading to improved performance and resource utilization in a
wide range of applications, including data processing, optimization problems, artificial
intelligence, and much more.
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
3 Write a Program to sort a given set of elements using the Quick Sort C325.3 9
4 Write a Program to sort a given set of elements using the Merge Sort C325.4 12
5 Write a Program to sort a given set of elements using the Selection Sort C325.3 16
6 Write a Program for implementation of Fractional Knapsack problem using Greedy C325.2, 19
Method and 0/1 Knapsack problem using Dynamic Programming. C325.1
7 Write a Program to find the shortest path from a given vertex to other vertices C325.3 23
in a weighted connected graph using Dijkstra’s algorithm.
8 Write a Program to find the minimum cost spanning tree (MST) of a given C325.2, 26
undirected graph using Kruskal’s algorithm/Prim’s Algorithms. C325.3
9 Write a Program to implement N-Queens problem using back tracking C325.4 33
10 Write a Program to check whether a given graph is connected or not using DFS C325.3, 37
method. C325.2
DOs
1. Login-on with your username and password.
2. Log off the computer every time when you leave the Lab.
3. Arrange your chair properly when you are leaving the lab.
4. Put your bags in the designated area.
5. Ask permission to print.
DON’Ts
1. Do not share your username and password.
2. Do not remove or disconnect cables or hardware parts.
3. Do not personalize the computer setting.
4. Do not run programs that continue to execute after you log off.
5. Do not download or install any programs, games or music on computer in Lab.
6. Personal Internet use chat room for Instant Messaging (IM) and Sites is strictly
prohibited.
7. No Internet gaming activities allowed.
8. Tea, Coffee, Water & Eatables are not allowed in the Computer Lab.
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Emergency : Reception
(Reception) Security : Front Gate
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
All students are required to maintain a record of the experiments conducted by them. Guidelines
for its preparation are as follows: -
1) All files must contain a title page followed by an index page. The files will not be signed
by the faculty without an entry in the index page.
2) Student’s Name, Roll number and date of conduction of experiment must be written on
all pages.
3) For each experiment, the record must contain the following
(i) Aim/Objective of the experiment
(ii) Pre-experiment work (as given by the faculty)
(iii) Lab assignment questions and their solutions
(iv) Test Cases (if applicable to the course)
(v) Results/ output
Note:
1. Students must bring their lab record along with them whenever they come for the lab.
LAB EXPERIMENTS
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 1
OBJECTIVE:
Write a Program for iterative and recursive Binary Search.
BRIEF DESCRIPTION:
Binary Search is defined as a searching algorithm used in a sorted array by repeatedly dividing
the search interval in half. The idea of binary search is to use the information that the array is
sorted and reduce the time complexity to O (log N).
To apply Binary Search algorithm:
The data structure must be sorted.
Access to any element of the data structure takes constant time.
In this algorithm,
Divide the search space into two halves by finding the middle index “mid”.
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated.
If the key is not found at middle element, choose which half will be used as the next
search space.
o If the key is smaller than the middle element, then the left side is used for next
search.
o If the key is larger than the middle element, then the right side is used for next
search.
This process is continued until the key is found or the total search space is exhausted.
The Binary Search Algorithm can be implemented in the following two ways:
Iterative Binary Search Algorithm
Recursive Binary Search Algorithm
PRE-EXPERIMENT QUESTIONS:
What is binary search?
How does the binary search algorithm work, and what are its main steps?
Discuss the time complexity of the binary search algorithm. Is it efficient compared to other
search algorithms?
1
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
#include <iostream>
using namespace std;
if (arr[mid] == target)
return mid;
return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
return 0;
}
Output:
Students will be able to recognize actual position of element in iterative way as shown below:
2
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
if (arr[mid] == target)
return mid;
return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
return 0;
}
Output:
Students will be able to recognize actual position of element in recursive way as shown below:
3
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
4
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 2
OBJECTIVE:
Write a Program for iterative and recursive Linear Search.
BRIEF DESCRIPTION:
Linear search, also known as sequential search, is a simple and straightforward searching
algorithm used to find an element within a collection of items. It is applicable to both ordered
and unordered lists.
The linear search algorithm starts at the beginning of the list and compares each element
sequentially until a match is found or the end of the list is reached. If the target element is found,
the search terminates, and the index or position of the element is returned. If the end of the list is
reached without finding a match, the search concludes, and a special value (e.g., -1) is typically
returned to indicate that the element was not found.
Linear search is intuitive and easy to implement. It works well for small lists or when the target
element is located near the beginning of the list. However, its performance is linear with respect
to the size of the list, resulting in a worst-case time complexity of O(n), where n is the number of
elements in the list. This means that as the size of the list grows, the time required for the search
increases linearly.
Linear search is often used when:
The list is unsorted or only partially sorted.
The list is small.
The cost of sorting the list in advance is not justified.
The search is infrequent or not time-critical.
PRE-EXPERIMENT QUESTIONS:
What is linear search, and how does it work?
What is the time complexity of linear search, and when is it suitable to use?
What are the advantages and disadvantages of linear search?
5
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
return -1;
}
int main() {
int arr[] = {5, 12, 8, 2, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 23;
return 0;
}
Output:
Students will be able to recognize actual position of element in iterative way in unsorted way as shown
below:
6
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
#include <iostream>
using namespace std;
if (arr[left] == target)
return left;
int main() {
int arr[] = {5, 12, 8, 2, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 23;
return 0;
}
Output:
Students will be able to recognize actual position of element in recursive way in unsorted way as
shown below:
7
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
8
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 3
OBJECTIVE:
Write a Program to sort a given set of elements using the Quick Sort.
BRIEF DESCRIPTION:
Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given an array around the picked pivot.
There are many different versions of Quick Sort that pick pivot in different ways.
Always pick first element as pivot.
Always pick last element as pivot (implemented below)
Pick a random element as pivot.
Pick median as pivot.
The key process in Quick Sort is partition. Target of partitions is, given an array and an element
x of array as pivot, put x at its correct position in sorted array and put all smaller elements
(smaller than x) before x, and put all greater elements (greater than x) after x.
In this program, the partition function is responsible for rearranging the elements around a pivot
element, such that all elements less than the pivot are on its left, and all elements greater than the
pivot are on its right. It returns the index of the pivot element.
The quick_sort function recursively partitions the array using the pivot element's index. It then
applies the quick_sort function to the sub-arrays formed by the partitioning.
Sort a given set of elements using the Quick sort method and determine the time required to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list
to be sorted and 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.
PRE-EXPERIMENT QUESTIONS:
Explain the concept of divide and conquer.
Define in place sorting algorithm.
List different ways of selecting pivot element.
9
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
// Partition the array and return the index of the pivot element
int partition(vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
int main() {
vector<int> elements = {9, 5, 1, 3, 8, 6, 2, 7, 4};
return 0;
}
10
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Output:
Students will be able to sort the given array with the help of Pivot element as shown below:
11
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 4
OBJECTIVE:
Write a Program to sort a given set of elements using the Merge Sort.
BRIEF DESCRIPTION:
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself
for the two halves and then merges the two sorted halves.
The merge () function is used for merging two halves. The merge (a, low, mid, high) is key
process that assumes that a [low, mid] and a [mid+1, high] are sorted and merges the two sorted
sub-arrays into one.
In this program, the merge function merges two sorted subarrays (left and right) into a single
sorted array. It uses three indices (i, j, and k) to traverse the subarrays and the merged array.
The merge_sort function recursively divides the array into two halves and applies the merge_sort
function to each half. It then merges the sorted halves using the merge function.
In the main function, we define the elements vector with the input set of elements. The vector is
printed before and after sorting using the Merge Sort algorithm.
Implement merge sort algorithm to sort a given set of elements and determine the time required
to sort the elements. Repeat the experiment for different values of n, the number of elements in
the list to be sorted and 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.
While comparing two sub lists for merging, the first element of both lists is taken into
consideration. While sorting in ascending order, the element that is of a lesser value becomes a
new element of the sorted list. This procedure is repeated until both the smaller sub lists are
empty and the new combined sub list comprises all the elements of both the sub lists.
PRE-EXPERIMENT QUESTIONS:
What is the running time of merge sort?
What technique is used to sort elements in merge sort?
Is merge sort in place sorting algorithm?
12
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
vector<int> left(left_size);
vector<int> right(right_size);
13
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
int main() {
vector<int> elements = {9, 5, 1, 3, 8, 6, 2, 7, 4};
return 0;
}
14
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Output:
Students will be able to identify sorting with divide and conquer technique as shown below:
15
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 5
OBJECTIVE:
Write a Program to sort a given set of elements using the Selection Sort.
BRIEF DESCRIPTION:
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the
smallest (or largest) element from the unsorted portion of the list and moving it to the sorted
portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of
the list and swaps it with the first element of the unsorted part. This process is repeated for the
remaining unsorted portion until the entire list is sorted.
Advantages of Selection Sort Algorithm:
Simple and easy to understand.
Works well with small datasets.
In this algorithm, the array is divided into two parts, first is sorted part, and another one is the
unsorted part. Initially, the sorted part of the array is empty, and unsorted part is the given array.
Sorted part is placed at the left, while the unsorted part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the
first position. After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.
This program defines a function selectionSort to perform the Selection Sort algorithm on the
given array. It iterates through the array and selects the minimum element in each iteration and
swaps it with the first unsorted element. The program also includes a helper function printArray
to print the elements of an array.
PRE-EXPERIMENT QUESTIONS:
Is Selection Sort Algorithm stable?
Is Selection Sort Algorithm in-place?
Does Selection Sort have any advantages or disadvantages compared to other sorting
algorithms?
16
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
int main() {
int arr[] = {64, 25, 12, 22, 11};
int size = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, size);
return 0;
}
17
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Output:
Students will be able to analysis elements position with larger space taken by them as shown
below:
18
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 6
OBJECTIVE:
Write a Program for implementation of Fractional Knapsack problem using Greedy Method and
0/1 Knapsack problem using Dynamic Programming.
BRIEF DESCRIPTION:
Fractional Knapsack Problem:
Given the weights and profits of N items, in the form of {profit, weight} put these items in a
knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional Knapsack,
we can break items for maximizing the total value of the knapsack.
The basic idea of the greedy approach is to calculate the ratio profit/weight for each item and sort
the item on the basis of this ratio. Then take the item with the highest ratio and add them as much
as we can (can be the whole element or a fraction of it).
This will always give the maximum profit because, in each step it adds an element such that this
is the maximum possible profit for that much weight.
Example:
Input: arr [] = {{60, 10}, {100, 20}, {120, 30}}, W = 50
Output: 240
Explanation: By taking items of weight 10 and 20 kg and 2/3 fraction of 30 kg.
Hence total price will be 60+100+(2/3) (120) = 240.
Example:
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.
19
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
PRE-EXPERIMENT QUESTIONS:
What is the time complexity of the Greedy algorithm for the Fractional Knapsack
problem?
What is the main advantage of using the Greedy method for the Fractional Knapsack
problem?
How does the time complexity of the Dynamic Programming approach for the 0/1
Knapsack problem depend on the number of items and the knapsack capacity?
struct Item {
int weight;
int value;
double valuePerWeight;
return totalValue;
}
int main() {
int capacity = 50;
std::vector<Item> items = {
Item(10, 60),
Item(20, 100),
20
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Item(30, 120),
};
std::cout << "Maximum value in the knapsack: " << maxValue << std::endl;
return 0;
}
Output:
Students will be able to calculate maximum and optimal profit using Greedy approach as shown
below:
int knapsack(int capacity, const std::vector<int>& weights, const std::vector<int>& values, int n) {
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(capacity + 1, 0));
return dp[n][capacity];
}
int main() {
int capacity = 50;
std::vector<int> weights = {10, 20, 30};
21
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
std::cout << "Maximum value in the knapsack: " << maxValue << std::endl;
return 0;
}
Output:
Students will be able to calculate maximum and optimal profit using Greedy approach as shown
below:
22
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 7
OBJECTIVE:
Write a Program to find the shortest path from a given vertex to other vertices in a weighted
connected graph using Dijkstra’s algorithm.
BRIEF DESCRIPTION:
Given a graph and a source vertex in the graph, find the shortest paths from the source to all
vertices in the given graph.
Example:
Output: 0 4 12 19 21 11 9 8 14
Explanation: The distance from 0 to 1 = 4.
The minimum distance from 0 to 2 = 12. 0->1->2
The minimum distance from 0 to 3 = 19. 0->1->2->3
The minimum distance from 0 to 4 = 21. 0->7->6->5->4
The minimum distance from 0 to 5 = 11. 0->7->6->5
The minimum distance from 0 to 6 = 9. 0->7->6
The minimum distance from 0 to 7 = 8. 0->7
The minimum distance from 0 to 8 = 14. 0->1->2->8
PRE-EXPERIMENT QUESTIONS:
What is the time complexity of Dijkstra’s algorithm?
Define cost matrix.
Define directed graph.
23
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
while (!pq.empty()) {
int u = pq.top().first;
int uDist = pq.top().second;
pq.pop();
// Skip if the current distance is already greater than the stored distance
if (uDist > dist[u]) {
continue;
}
int main() {
int numVertices = 5;
std::vector<std::vector<pii>> graph(numVertices);
24
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
graph[2].push_back({4, 5});
graph[3].push_back({4, 2});
int startVertex = 0;
std::vector<int> dist;
return 0;
}
Output:
Students will be able to find shortest map and understand the application GOOGLE MAPS as
shown below:
25
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 8
OBJECTIVE:
Write a Program to find the minimum cost spanning tree (MST) of a given undirected graph
using Kruskal’s algorithm/Prim’s Algorithms.
BRIEF DESCRIPTION:
Both Prim’s and Kruskal’s algorithm finds the Minimum Spanning Tree and follow the Greedy
approach of problem-solving, but there are few major differences between them.
Prim’s algorithm runs faster in dense Kruskal’s algorithm runs faster in sparse
graphs. graphs.
It generates the minimum spanning tree It generates the minimum spanning tree
starting from the root vertex. starting from the least weighted edge.
26
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
PRE-EXPERIMENT QUESTIONS:
Why Prim’s and Kruskal's MST algorithm fails for Directed Graph?
Can Kruskal's algorithm and Prim's algorithm handle graphs with cycles? Why or why
not?
What is the time complexity of Kruskal's algorithm and Prim's algorithm?
#include <iostream>
#include <vector>
#include <algorithm>
struct Edge {
int src;
int dest;
int weight;
struct Graph {
int numVertices;
std::vector<Edge> edges;
Graph(int numVertices)
: numVertices(numVertices) {}
27
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
struct DisjointSet {
std::vector<int> parent;
std::vector<int> rank;
DisjointSet(int size) {
parent.resize(size);
rank.resize(size);
int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
};
DisjointSet disjointSet(graph.numVertices);
28
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
if (srcRoot != destRoot) {
mst.push_back(edge);
disjointSet.unite(srcRoot, destRoot);
}
}
return mst;
}
int main() {
int numVertices = 4;
Graph graph(numVertices);
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 6);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 3, 4);
return 0;
}
Output:
Students will be able to implement Kruskal’s algorithm as shown below:
29
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
struct Edge {
int dest;
int weight;
struct Graph {
int numVertices;
std::vector<std::vector<Edge>> adjList;
Graph(int numVertices)
: numVertices(numVertices), adjList(numVertices) {}
int startVertex = 0;
dist[startVertex] = 0;
pq.push(Edge(startVertex, 0));
while (!pq.empty()) {
int u = pq.top().dest;
pq.pop();
visited[u] = true;
30
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
int v = edge.dest;
int weight = edge.weight;
return mst;
}
int main() {
int numVertices = 4;
Graph graph(numVertices);
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 6);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 3, 4);
return 0;
}
Output:
Students will be able to implement Prim’s algorithm as shown below:
31
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
32
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 9
OBJECTIVE:
Write a Program to implement N-Queens problem using back tracking.
BRIEF DESCRIPTION:
Backtracking is an algorithmic technique for solving problems recursively by trying to build a
solution incrementally, one piece at a time, removing those solutions that fail to satisfy the
constraints of the problem at any point in time (by time, here, is referred to the time elapsed till
reaching any level of the search tree).
Backtracking can also be said as an improvement to the brute force approach. So basically, the
idea behind the backtracking technique is that it searches for a solution to a problem among all
the available options. Initially, we start the backtracking from one possible option and if the
problem is solved with that selected option then we return the solution else we backtrack and
select another option from the remaining available options. There also might be a case where
none of the options will give you the solution and hence we understand that backtracking won’t
give any solution to that particular problem. We can also say that backtracking is a form of
recursion.
This is because the process of finding the solution from the various option available is repeated
recursively until we don’t find the solution or we reach the final state. So we can conclude that
backtracking at every step eliminates those choices that cannot give us the solution and proceeds
to those choices that have the potential of taking us to the solution.
There are three types of problems in backtracking –
Decision Problem – In this, we search for a feasible solution.
Optimization Problem – In this, we search for the best solution.
Enumeration Problem – In this, we find all feasible solutions.
This program solves the N-Queens problem using backtracking. The printBoard function is used
to display the board configuration. The isSafe function checks if it is safe to place a queen in a
particular position on the board. The solveNQueensUtil function recursively places queens in
safe positions and backtracks when a solution is found or when it reaches an unsafe
configuration. The solveNQueens function initializes the board and calls solveNQueensUtil to
find and print all the valid solutions. In the main function, the program sets N as the number of
queens and the size of the board.
PRE-EXPERIMENT QUESTIONS:
What is backtracking, and how does it work in the context of problem-solving?
How does backtracking solve the N-Queens problem?
What is the time complexity of the backtracking solution for the N-Queens problem?
33
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
return true;
}
34
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
void solveNQueens(int N) {
std::vector<std::vector<char>> board(N, std::vector<char>(N, '.'));
int count = 0;
solveNQueensUtil(board, 0, N, count);
int main() {
int N = 4; // Number of queens and size of the board
solveNQueens(N);
return 0;
}
Output:
Students will be able to implement the concept of backtracking and can solve puzzles such as
Sudoku as shown below:
35
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
36
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 10
OBJECTIVE:
Write a Program to check whether a given graph is connected or not using DFS method.
BRIEF DESCRIPTION:
Both DFS and BFS are widely used graph traversal algorithms with different characteristics.
DFS explores deeply before backtracking, while BFS explores broadly in a level-by-level
manner. The choice between DFS and BFS depends on the problem requirements and the
structure of the graph being traversed.
Depth-First Search is a graph traversal algorithm that explores vertices and their edges in a depth
ward motion. It starts from a selected vertex and explores as far as possible along each branch
before backtracking. DFS uses a stack (either an explicit stack or the call stack) to keep track of
vertices to visit. The algorithm marks each visited vertex to avoid revisiting it. DFS is often
implemented using recursion, where the function calls itself to explore neighboring vertices. It is
useful for solving problems such as finding connected components, detecting cycles, and
traversing trees or graphs.
Breadth-First Search is a graph traversal algorithm that explores vertices and their edges in a
breadth ward motion. It starts from a selected vertex and visits all of its neighboring vertices
before moving on to their neighbors. BFS uses a queue to keep track of vertices to visit. The
first-in, first-out (FIFO) order ensures visiting vertices in increasing order of distance from the
starting vertex. The algorithm marks each visited vertex to avoid revisiting it. BFS is often
implemented using a while loop that dequeues a vertex, explores its neighbors, and enqueues
them for further exploration. It is useful for solving problems such as finding the shortest path,
finding connected components, and traversing trees or graphs in a level-by-level manner.
This program checks whether a given graph is connected or not using the DFS method. The DFS
function performs a depth-first search traversal starting from a given vertex and marks all visited
vertices. The isConnected function initializes a vector to track the visited status of each vertex
and calls the DFS function starting from the first vertex. It then checks if all vertices are visited
to determine if the graph is connected.
In the main function, a sample graph is created using an adjacency list representation. The graph
is then passed to the isConnected function, and based on the result, it prints whether the graph is
connected or not.
PRE-EXPERIMENT QUESTIONS:
What does it mean for a graph to be connected?
What is the main difference between a connected graph and a disconnected graph?
How can we determine whether a graph is connected or disconnected?
37
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
return true;
}
int main() {
int numVertices = 5;
std::vector<std::vector<int>> graph(numVertices);
if (connected) {
std::cout << "The graph is connected." << std::endl;
} else {
std::cout << "The graph is not connected." << std::endl;
}
return 0;
}
38
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Output:
Students will be able to analysis the connected or disconnected graph performance as shown
below:
39
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
LAB EXPERIMENT 11
OBJECTIVE:
Write a program to implement the Travelling Salesman Problem (TSP).
BRIEF DESCRIPTION:
Given a set of cities and the distance between every pair of cities, the problem is to find the
shortest possible route that visits every city exactly once and returns to the starting point. Note
the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if
there exists a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists
(because the graph is complete) and in fact, many such tours exist, the problem is to find a
minimum weight Hamiltonian Cycle.
For example, consider the graph shown in the figure on the right side. A TSP tour in the graph is
1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. The problem is a famous NP-hard
problem. There is no polynomial-time know solution for this problem. The following are
different solutions for the traveling salesman problem.
PRE-EXPERIMENT QUESTIONS:
What is the Traveling Salesman Problem (TSP)?
What is the significance of the TSP in the field of computer science?
What are the different approaches to solving the TSP?
40
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Program Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
// Find the minimum cost of reaching the starting vertex from any other vertex
int minCost = INT_MAX;
for (int last = 1; last < n; ++last) {
int cost = graph[last][0] + dp[numSubsets - 1][last];
minCost = std::min(minCost, cost);
}
return minCost;
}
int main() {
int n = 4; // Number of cities
41
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
std::cout << "Minimum cost for the TSP: " << minCost << std::endl;
return 0;
}
Output:
Students will be able to implement TSP using dynamic programming as shown below:
42
Department of CSE DESIGN & ANALYSIS OF ALGORITHMS USING C++ LAB (LC-CSE-325G) 2023-2024
Crosschecked By
HOD CSE
43