Nagindas Khandwala College of Commerce, Arts & Management Studies & Shantaben Nagindaskhandwala College of Science Malad (W), Mumbai - 64

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

MALAD KANDIVALI EDUCATION SOCIETY’S

NAGINDAS KHANDWALA COLLEGE OF COMMERCE, ARTS &


MANAGEMENT STUDIES & SHANTABEN
NAGINDASKHANDWALA COLLEGE OF SCIENCE
MALAD [W], MUMBAI – 64

AUTONOMOUS INSTITUTION
(Affiliated To University Of Mumbai)

Reaccredited ‘A’ Grade by NAAC | ISO 9001:2015 Certified

CERTIFICATE

Name: Aditya Mahendra Sahu


Roll No: 329 Programme: BSc IT Semester: IV

This is certified to be a bonafide record of practical work done by the above student in the
college laboratory for the course DESIGN AND ANALYSIS OF
ALGORITHM(2142UISDA) for the partial fulfilment of FourthSemester of BSc IT during
the academic year 2021-22.
The journal work is the original study work that has been duly approved in the year 2021-22
by the undersigned.

External Examiner Ms. Swapnali Tandel


(Subject-In-Charge)

Date of Examination: (College Stamp)


Name : Aditya Mahendra Sahu Roll No : 329 Class : SYIT

N
DATE TITLE Page No SIGN
O
1a. Implement Insertion
Sort 1b. Implement Bubble
1. 4-12-2021 Sort 1c. Implement 1
Selection Sort 1d.
Implement Quick Sort 1e.
Implement Merge Sort
Implement Knapsack problem using
2. 11-12-2021 7
Dynamic Programming

From a given vertex in a weighted connected


8
3. 18-12-2021 graph, find shortest paths to other vertices using
Dijkstra’s algorithm.

Find Minimum Cost Spanning Tree of a 10


4. 8-01-2022
given undirected graph using Kruskal’s
algorithm.

5. 15-01-2022 Perform various tree traversal algorithms for 12


a given tree.

Print all the nodes reachable from a given 14


6. 22-01-2022
starting node in a digraph using both BFS and dfs
methods.
Implement any scheme to find the optimal solution
for the Traveling Salesperson problem and then 17
7. 29-01-2022 solve the same problem instance using any
approximation algorithm and determine the error
in the approximation.

Find Minimum Cost Spanning Tree of a


8. 5-02-2022 19
given undirected graph using Prim’s
algorithm.

Find Minimum Cost Spanning Tree of a 22


9. 12-02-2022
given undirected graph using Prim’s
algorithm.
Practical 1
A)
Aim:- Implement Insertion Sort.

Theory:- Insertion sort is a simple sorting algorithm that works the way we sort
playing cards in our hands.

Code:-

Output:-

1
B)
Aim:- Implement Bubble Sort.

Theory:- Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.

Code:-

Output:-

2
C)
Aim:- Implement Selection Sort.

Theory:- The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and putting
it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the sorted subarray.
Code:-

Output:-

3
D)
Aim:- Implement Quick Sort.

Theory:- QuickSort is a Divide and Conquer algorithm. It picks an element as pivot


and partitions the given array around the picked pivot. There are many different
versions of quickSort that pick pivot in different ways.

1. Always pick first element as pivot.

2. Always pick last element as pivot (implemented below)

3. Pick a random element as pivot.

4. Pick median as pivot.

The key process in quickSort 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. All this should be done in linear time.

Code:-

4
Output:-

E)
Aim:- Implement Merge Sort.

Theory:- Merge Sort is a Divide and Conquer algorithm. It divides input array
intwo 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(arr, l,m, r) is key
process that assumes that arr[l..m] and arr[m+1..r] are sorted andmerges the two
sorted sub-arrays into one.

Code:-

5
Output:-

6
Practical 2
Aim:- Implement Knapsack problem using Dynamic Programming.

Theory:- Here knapsack is like a container or a bag. Suppose we have given some
items which have some weights or profits. We have to put some items in the
knapsack in such a way total value produces a maximum profit.

For example, the weight of the container is 20 kg. We have to select the items in
such a way that the sum of the weight of items should be either smaller than or
equal to the weight of the container, and the profit should be maximum.

There are two types of knapsack problems:

1. 0/1 knapsack problem.

2. Fractional knapsack problem.

Code:-

Output:-

7
Practical 3
Aim:- From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra’s algorithm.

Theory:- Given a directed graph and a source vertex in the graph, the task is to find
the shortest distance and path from source to target vertex in the given graph
where edges are weighted (non-negative) and directed from parent vertex to source
vertices.

Approach:

1. Mark all vertices unvisited. Create a set of all unvisited vertices.

2. Assign zero distance value to source vertex and infinity distance value to all
other vertices.

3. Set the source vertex as current vertex

4. For current vertex, consider all of its unvisited children and calculate their
tentative distances through the current. (distance of current + weight of the
corresponding edge) Compare the newly calculated distance to the current assigned
value (can be infinity for some vertices) and assign the smaller one.

5. After considering all the unvisited children of the current vertex, mark the
current as visited and remove it from the unvisited set.

6. Similarly, continue for all the vertex until all the nodes are visited.

Code:-

8
Output:-

9
Practical 4
Aim:- Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s
algorithm.

Theory:- Given a connected and undirected graph, a spanning tree of that graph is
a subgraph that is a tree and connects all the vertices together. A single graph can
have many different spanning trees. A minimum spanning tree (MST) or minimum
weight spanning tree for a weighted, connected, undirected graph is a spanning tree
with a weight less than or equal to the weight of every other spanning tree. The
weight of a spanning tree is the sum of weights given to each edge of the spanning
tree.

A minimum spanning tree has (V – 1) edges where V is the number of vertices in the
given graph.

Code:-

10
Output:-

11
Practical 5
Aim:- Perform various tree traversal algorithms for a given tree.

Theory:- Unlike linear data structures (Array, Linked List, Queues, Stacks, etc)
which have only one logical way to traverse them, trees can be traversed in
different ways. Following are the generally used ways for traversing trees.

• Depth First Traversals:

(a) Inorder (Left, Root, Right) : 4 2 5 1 3

(b) Preorder (Root, Left, Right) : 1 2 4 5 3

(c) Postorder (Left, Right, Root) : 4 5 2 3 1 Breadth-First or Level Order Traversal:


12345

• Uses of Inorder

In the case of binary search trees (BST), Inorder traversal gives nodes in non-
decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder
traversal where Inorder traversal s reversed can be used.

Example: In order traversal for the above-given figure is 4 2 5 1 3.

• Uses of Preorder

Preorder traversal is used to create a copy of the tree. Preorder traversal is also
used to get prefix expression on an expression tree.

Example: Preorder traversal for the above-given figure is 1 2 4 5 3.

• Uses of Postorder

Postorder traversal is used to delete the tree.Postorder traversal is also useful to get
the postfix expression of an expression tree.Example: Postorder traversal for the
above-given figure is 4 5 2 3 1.

Code:-

12
Output:-

13
Practical 6
Aim:- Print all the nodes reachable from a given starting node in a digraph using
both BFS and dfs methods.

Theory:- 1. Breadth First Search:


BFS explores graph moving across to all the neighbors of last visited vertex
traversals i.e., it proceeds in a concentric manner by visiting 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 in the same connected component as the starting vertex
are visited. Instead of a stack, BFS uses queue.

Complexity: BFS has the same efficiency as DFS: it is Θ (V2) for Adjacency matrix
representation and Θ (V+E) for Adjacency linked list representation.

2. Depth First Traversal (or Search) for a graph is similar to Depth First Traversal
of a tree. The only catch here is, unlike trees, graphs may contain cycles (a node may
be visited twice). To avoid processing a node more than once, use a boolean visited
array.

Depth-first search is an algorithm for traversing or searching tree or graph data


structures. The algorithm starts at the root node (selecting some arbitrary node as
the root node in the case of a graph) and explores as far as possible along each
branch before backtracking. So the basic idea is to start from the

root or any arbitrary node and mark the node and move to the adjacent unmarked
node and continue this loop until there is no unmarked adjacent node. Then
backtrack and check for other unmarked nodes and traverse them. Finally, print the
nodes in the path.

• Algorithm:

Create a recursive function that takes the index of the node and a visited array.

Mark the current node as visited and print the node.

Traverse all the adjacent and unmarked nodes and call the recursive function with
the index of the adjacent node.

14
Code:

15
16
Output:-

17
Practical 7
Aim:- Implement any scheme to find the optimal solution for the Traveling
Salesperson problem and then solve the same problem instance using any
approximation algorithm and determine the error in the approximation.

Theory:-
Algorithm

1. Start on an arbitrary vertex as current vertex.

2. Find out the shortest edge connecting current vertex and an unvisited vertex
V.

3. Set current vertex to V.

4. Mark V as visited.

5. If all the vertices in domain are visited, then terminate.

6. Go to step 2.

7. The sequence of the visited vertices. is the output of the algorithm.

Code:-

18
Output:-

19
Practical 8
Aim:- Find Minimum Cost Spanning Tree of a given undirected graph usingPrim’s
algorithm.

Theory:- Prim’s algorithm is a Greedy algorithm. It 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, 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 set of vertices in a graph is called cut in graph
theory. So, at every step of Prim’s algorithm, we find a cut (of two sets, one contains
the vertices already included in MST and other contains rest of the vertices), pick
the minimum weight edge from the cut and include this vertex to MST Set (the set
that contains already included vertices).

How does Prim’s Algorithm Work? The idea behind Prim’s algorithm is simple, a
spanning tree means all vertices must be connected. So the two disjoint subsets
(discussed above) of vertices must be connected to make a Spanning Tree. And they
must be connected with the minimum weight edge to make it a Minimum Spanning
Tree.

Algorithm

1) Create a set mstSet that keeps track of vertices already included in MST.

2) Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE. Assign key value as 0 for the first vertex so that it is picked first.

3) While mstSet doesn’t include all vertices.

a) Pick a vertex u which is not there in mstSet and has minimum key value.

b) Include u to mstSet.

c) Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v

20
The idea of using key values is to pick the minimum weight edge from cut. The key
values are used only for vertices which are not yet included in MST, the key value
for these vertices indicate the minimum weight edges connecting them to the set of
vertices included in MST.

Code:-

21
Output:-

22
Practical 9
Aim:- Implement N Queen's problem usingBacktracking.

Theory:- The N Queen is the problem of placing N chess queens on an N×N


chessboard so that no two queens attack each other.

Algorithm:

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.

Code:-

23
Output:-

24

You might also like