DAA Practical Jinesh
DAA Practical Jinesh
Practical File
On
Affiliated to
Submitted by : Submitted to :
Jinesh Jain Mr. Rishiraj Vyas
Roll no.: Assistant Professor
21EEBCS052 (Department of CSE)
INDEX
1 Sort a given set of elements using the Quicksort 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.
2 Implement a parallelized 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.
6 Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.
7 a. Print all the nodes reachable from a given starting node in a digraph using BFS method.
b. Check whether a given graph is connected or not using DFS method.
8 Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.
Q1.
a.] Sort a given set of elements using the Quicksort method
and determine the time required to sort the elements.
ANS.
import random
import time
import matplotlib.pyplot as plt
def quicksort(arr):
#quicksort Function: Implements the Quicksort algorithm recursively.
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
def measure_time_quicksort(arr):
#measure_time_quicksort Function: Measures the time taken to sort an array
using Quicksort.
start_time = time.time()
quicksort(arr)
end_time = time.time()
return end_time - start_time
list_sizes, times
ANS.
The plot shows that the time complexity of Quicksort is approximately O(nlogn),
which is evident from the gradual increase in time with respect to the number of
elements.
Q2.]
a.] Implement a parallelized merge sort algorithm to sort a
given set of elements and determine the time required to sort the
elements.
ANS.
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each
containing about half of the elements of A[p .. r]. That is, q is the halfway point
of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted
subarrays A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this
step, we will define a procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the subarray has just one element, so
that it is trivially sorted.
#CODE:
import time
import random
import matplotlib.pyplot as plt
from concurrent.futures import ThreadPoolExecutor
def parallel_merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
with ThreadPoolExecutor(max_workers=2) as executor:
left_future = executor.submit(parallel_merge_sort, arr[:mid])
right_future = executor.submit(parallel_merge_sort, arr[mid:])
left = left_future.result()
right = right_future.result()
return merge(left, right)
ANS.
def measure_time(n):
arr = [random.randint(0, 10000) for _ in range(n)]
start_time = time.time()
parallel_merge_sort(arr)
end_time = time.time()
return end_time - start_time
Soln.
ANS.
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of
vertices such that for every directed edge uv, vertex u comes before v in the
ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
Input parameters: int a[MAX][MAX] - adjacency matrix of the input graph int n - no
of vertices in the graph
CODE :
#include <stdio.h>
for (i=0;i<n;i++){
in[i] = 0;
for (j=0; j<n; j++)
if (a[j][i] == 1)
in[i]++;
}
while(1){
for (i=0;i<n;i++){
if (in[i] == 0){
stack[++top] = i;
in[i] = -1;
}
}
if (top == -1)
break;
out[k] = stack[top--];
for (i=0;i<n;i++){
if (a[out[k]][i] == 1)
in[i]--;
}
k++;
}
OUTPUT
Ans.
class Graph:
OUTPUT
Ans.
Problem Definition
Items: n items each with a weight wi and vi .
Knapsack Capacity: W.
Objective: Maximize the total value of items in the knapsack without
exceeding its weight capacity.
CODE
def knapsack(values, weights, capacity):
n = len(values)
Ans.
7. We will now select the next unvisited node with the least path and visit it.
Hence, we will visit node B and perform relaxation on its unvisited
neighbors. After performing relaxation, the path to node C will remain 5,
whereas the path to node E will become 11, and the path to node D will
become 13.
8. We will now visit node E and perform relaxation on its neighboring nodes B,
D, and F. Since only node F is unvisited, it will be relaxed. Thus, the path to
node B will remain as it is, i.e., 4, the path to node D will also remain 13,
and the path to node F will become 14 (8 + 6).
9. Now we will visit node D, and only node F will be relaxed. However, the
path to node F will remain unchanged, i.e., 14.
10. Since only node F is remaining, we will visit it but not perform any
relaxation as all its neighboring nodes are already visited.
Once all the nodes of the graphs are visited, the program will end.
OUTPUT
A=0
B = 4 (A -> B)
C = 5 (A -> C)
D = 4 + 9 = 13 (A -> B -> D)
E = 5 + 3 = 8 (A -> C -> E)
F = 5 + 3 + 6 = 14 (A -> C -> E -> F)
Q6. Find Minimum Cost Spanning Tree of a given undirected graph
using Kruskal's algorithm.
Ans.
It falls under a class of algorithms called greedy algorithms that find the local
optimum in the hopes of finding a global optimum.
We start from the edges with the lowest weight and keep adding edges until we
reach our goal.
The steps for implementing Kruskal's algorithm are as follows:
1. Sort all the edges from low weight to high
2. Take the edge with the lowest weight and add it to the spanning tree. If
adding the edge created a cycle, then reject this edge.
3. Keep adding edges until we reach all vertices.
EX:
Find the MST of the following:
Soln.
Q7.
a.] Print all the nodes reachable from a given starting node in a
digraph using BFS method.
Ans.
1. Initialization: Enqueue the starting node into a queue and mark it as visited.
2. Exploration: While the queue is not empty:
Dequeue a node from the queue and visit it (e.g., print its value).
For each unvisited neighbor of the dequeued node:
o Enqueue the neighbor into the queue.
o Mark the neighbor as visited.
3. Termination: Repeat step 2 until the queue is empty.
This algorithm ensures that all nodes in the graph are visited in a breadth-first
manner, starting from the starting node.
b.] Check whether a given graph is connected or not using DFS
method.
Ans.
Algorithm
1. Take two bool arrays vis1 and vis2 of size N (number of nodes of a graph)
and keep false in all indexes.
2. Start at a random vertex v of the graph G, and run a DFS(G, v).
3. Make all visited vertices v as vis1[v] = true.
4. Now reverse the direction of all the edges.
5. Start DFS at the vertex which was chosen at step 2.
6. Make all visited vertices v as vis2[v] = true.
7. If any vertex v has vis1[v] = false and vis2[v] = false then the graph is not
connected.
CORRECT INCORRECT
Q8. Find Minimum Cost Spanning Tree of a given undirected graph
using Prim’s algorithm.
Ans.
We start from one vertex and keep adding edges with the lowest weight until we
reach our goal.
The steps for implementing Prim's algorithm are as follows:
1. Initialize the minimum spanning tree with a vertex chosen at random.
2. Find all the edges that connect the tree to new vertices, find the minimum
and add it to the tree
3. Keep repeating step 2 until we get a minimum spanning tree
EX:
Find the MST of the following:
Soln.