DAA Lab Manual Answers
DAA Lab Manual Answers
L T P O Total
22CSE304 Design & Analysis of Algorithms
Credits
Lab Manual 2 1 2 0 4
Objectives
This course aims to provide the knowledge and understanding of the complexity issues of algorithms:
1. To introduce algorithms analysis and design techniques
2. To understand and design algorithms used for searching, sorting, and indexing operation
Outcomes
CLO 1: Analyzing complexity issues of algorithms
CLO 2: Ability to use the appropriate algorithm for searching, sorting, and indexing operations
CLO 3: Designing of new algorithms
CLO4: Students will be able to learn NP Class problems
Reference Materials
Textbooks (T) T1 T.H. Cormen, C.E. Leiserson, R.L. Rivest and C. Stein, “Introduction to Algorithms”,
Per availability in the library PHI Pvt. Ltd., 2012.
T2 Anany Levitin, “Introduction to the Design and Analysis of Algorithm”, Pearson
Education Asia, 2003.
T3 M.T.Goodrich and R.Tomassia, Algorithm Design: Foundations, Analysis and Internet
examples, Johnwiley and sons.
R1 R.C.T.Lee, S.S.Tseng, R.C.Chang and T.Tsai, Introduction to Design and Analysis of
Reference Books (R) Algorithms A strategic approach, McGraw-Hill Education (Asia) ,2005
R2 Aho, Ullman and Hopcroft, Design and Analysis of algorithms, Pearson Education India;
1st edition 2002
R3 Ellis Horowitz, Satraj Sahni and Rajasekharam, Fundamentals of Computer Algorithms,
Galgotia publications pvt. Ltd.
Journal Articles (J) J1 NA
provide link only
Case Material/ C1 NA
Whitepaper
provide link only
Any Other Sources O NA
Modules
Experiment Topics Total Contact CLO Mapping
No. Hours
UNIT-1
1. Write a program to implement the following algorithm using an 2
array as a data structure and analyse its time complexity.
a. Bubble sort,
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False CLO1
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
# Example usage:
my_array = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(my_array)
print("Sorted array using Bubble Sort:", my_array)
b. Selection sort
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example usage:
my_array = [64, 34, 25, 12, 22, 11, 90]
selection_sort(my_array)
print("Sorted array using Selection Sort:", my_array)
c. Insertion sort
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Example usage:
my_array = [64, 34, 25, 12, 22, 11, 90]
insertion_sort(my_array)
print("Sorted array using Insertion Sort:", my_array)
2. Write a program to implement Linear search and Binary search and 2 CLO1
analyze its time complexity. (Recursive/ non-recursive)
# Example usage:
my_array = [12, 114, 0, 4, 9]
target_value = 4
result = linear_search(my_array, target_value)
if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found")
b. Binary Search (Non-Recursive)
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# Example usage:
sorted_array = [0, 4, 9, 12, 114]
target_value = 4
result = binary_search(sorted_array, target_value)
if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found")
i, j, k = 0, 0, l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
b. Quick Sort
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
# Example usage:
my_array = [12, 11, 13, 5, 6, 7]
quickSort(my_array, 0, len(my_array) - 1)
print("Sorted array using Quick Sort:", my_array)
c. Heap Sort
def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n // 2, -1, -1):
heapify(arr, n, i)
# Example usage:
my_array = [12, 11, 13, 5, 6, 7]
heapSort(my_array)
print("Sorted array using Heap Sort:", my_array)
class Color(enum.Enum):
RED = enum.auto()
BLACK = enum.auto()
class RBNode:
def __init__(self, key):
self.color = Color.RED # New nodes are always red
self.key = key
self.leftChild = None
self.rightChild = None
self.parent = None
# Example usage:
root = RBNode(10)
root.color = Color.BLACK # Root is always black
class AVLTree:
def __init__(self):
self.root = None
root.height = 1 + max(self._get_height(root.left),
self._get_height(root.right))
balance = self._get_balance(root)
y.left = z
z.right = T2
z.height = 1 + max(self._get_height(z.left),
self._get_height(z.right))
y.height = 1 + max(self._get_height(y.left),
self._get_height(y.right))
return y
z.right = y
y.left = T3
y.height = 1 + max(self._get_height(y.left),
self._get_height(y.right))
z.height = 1 + max(self._get_height(z.left),
self._get_height(z.right))
return z
# Example usage:
avl_tree = AVLTree()
avl_tree.root = avl_tree.insert(avl_tree.root, 10)
avl_tree.root = avl_tree.insert(avl_tree.root, 20)
avl_tree.root = avl_tree.insert(avl_tree.root, 30)
# Example usage:
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50
print(knapSack(W, weight, profit, len(profit)))
# Example usage:
start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9]
print("The following activities are selected:")
printMaxActivities(start, finish)
class Node:
def __init__(self, symbol=None, frequency=None):
self.symbol = symbol
self.frequency = frequency
self.left = None
self.right = None
return priority_queue[0]
# Example usage:
tasks = [(1, 3), (2, 5), (4, 6), (5, 7), (7, 8)]
intervalScheduling(tasks)
6. Write programs (Single Source Shortest Path in Graph) 2 CLO3
a. To implement Dijkstra’s Algorithm.
import heapq
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
while pq:
d, u = heapq.heappop(pq)
# Example usage:
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 3)
g.add_edge(1, 2, 1)
g.add_edge(1, 3, 4)
g.add_edge(2, 4, 5)
src_vertex = 0
shortest_distances = g.dijkstra(src_vertex)
print(f"Shortest distances from vertex {src_vertex}:
{shortest_distances}")
b. To Implement Bellman-ford Algorithm
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
return dist
# Example usage:
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 3)
g.add_edge(1, 2, 1)
g.add_edge(1, 3, 4)
g.add_edge(2, 4, 5)
src_vertex = 0
shortest_distances = g.bellman_ford(src_vertex)
print(f"Shortest distances from vertex {src_vertex}:
{shortest_distances}")
7. Write programs (Minimum Spanning Tree) 2 CLO3
a. To implement Prim’s Algorithm.
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def prim_mst(self):
pq = [] # Priority queue to store vertices being processed
src = 0 # Starting vertex (can be any)
while pq:
u = heapq.heappop(pq)[1]
in_mst[u] = True
# Example usage:
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 3)
g.add_edge(1, 2, 1)
g.add_edge(1, 3, 4)
g.add_edge(2, 4, 5)
g.prim_mst()
def kruskal_mst(self):
result = []
self.graph.sort(key=lambda item: item[2])
parent = [i for i in range(self.V)]
rank = [0] * self.V
# Example usage:
g = Graph(4)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
g.kruskal_mst()
return dp[0][n - 1]
# Example usage:
matrices = [(10, 20), (20, 30), (30, 40), (40, 30)]
min_scalar_multiplications =
matrix_chain_multiplication(matrices)
print(f"Minimum scalar multiplications:
{min_scalar_multiplications}")
return ''.join(reversed(lcs))
# Example usage:
X = "AGGTAB"
Y = "GXTXAYB"
print("Longest Common Subsequence:",
longest_common_subsequence(X, Y))
9. a. Write a program to implement a backtracking 2 CLO4
algorithm for the N-queens problem.
def is_safe(board, row, col):
# Check if no queen attacks in the same column
for i in range(row):
if board[i][col] == 1:
return False
# Example usage:
my_set = [3, 34, 4, 12, 5, 2]
sum_to_find = 9
memo = [[-1] * (sum_to_find + 1) for _ in range(len(my_set) +
1)]
if subsetSumMemo(my_set, len(my_set), sum_to_find, memo):
print("Found a subset with the given sum")
else:
print("No subset with the given sum")
import random
from typing import List, Tuple
def generate_3SAT(num_vars: int, num_clauses: int) ->
List[Tuple[int, int, int]]:
problem = []
for _ in range(num_clauses):
clause = random.sample(range(1, num_vars + 1), 3)
clause = [random.choice([var, -var]) for var in clause]
problem.append(clause)
return problem
satisfied = 0
for clause in clauses:
for var in clause:
if (var > 0 and assignment[abs(var)-1]) or (var < 0 and not
assignment[abs(var)-1]):
satisfied += 1
break
return satisfied
for i in range(maxTries):
assignment = [random.choice([True, False]) for _ in
range(len(problem))]
for j in range(maxFlips):
if count_satisfied(problem, assignment) == len(problem):
return assignment
else:
best_var = None
best_satisfied = -1
for var in range(len(problem)):
flipped_assignment = assignment[:]
flipped_assignment[var] = not flipped_assignment[var]
num_satisfied = count_satisfied(problem,
flipped_assignment)
if num_satisfied > best_satisfied:
best_var = var
best_satisfied = num_satisfied
return None
for i in range(maxTries):
for j in range(maxFlips):
if count_satisfied(problem, assignment) == len(problem):
return assignment
else:
best_var = None
best_satisfied = -1
false_clauses = []
for clause in problem:
if all([(var > 0 and not assignment[abs(var)-1]) or (var
< 0 and assignment[abs(var)-1]) for var in clause]):
false_clauses.extend(clause)
for var in range(len(problem)):
flipped_assignment = assignment[:]
flipped_assignment[var] = not flipped_assignment[var]
num_satisfied = count_satisfied(problem,
flipped_assignment)
if num_satisfied > best_satisfied:
best_var = var
best_satisfied = num_satisfied
if random.random() < p:
var = random.choice(false_clauses)
else:
var = best_var
assignment[var] = not assignment[var]
return None
for i in range(maxTries):
assignment = [random.choice([True, False]) for _ in
range(len(problem))]
for j in range(maxFlips):
if count_satisfied(problem, assignment) == len(problem):
return assignment
else:
best_assignment = None
best_satisfied = -1
for i in range(maxTries):
population = [[random.choice([True, False]) for _ in
range(len(problem))] for _ in range(k)]
for j in range(maxFlips):
for assignment in population:
if count_satisfied(problem, assignment) == len(problem):
return assignment
else:
unsatisfied_clauses = [clause for clause in problem if
all([(var > 0 and not assignment[abs(var)-1]) or (var < 0 and
assignment[abs(var)-1]) for var in clause])]
c = random.choice(unsatisfied_clauses)
x = heuristic(c, assignment)
assignment[x] = not assignment[x]
return best_assignment
if __name__=='__main__':
num_problems = 10
num_vars = 50
num_clauses = 50
maxTries = 100
maxFlips = 100
p = 0.5
k=5
for i in range(num_problems):
problem = generate_3SAT(num_vars, num_clauses)
print("Solving problem ", i+1)
print("GSAT: ")
gsat_assignment = GSAT(problem[:], maxTries, maxFlips)
if gsat_assignment:
print("Solution found: ", gsat_assignment)
else:
print("No solution found!")
print("\n")
print("GSAT_RW: ")
gsat_rw_assignment = GSAT_RW(problem[:], maxTries,
maxFlips, p)
if gsat_rw_assignment:
print("Solution found: ", gsat_rw_assignment)
else:
print("No solution found.")
print("\n")
print("WSAT:")
wsat_assignment = WSAT(problem[:], maxTries, maxFlips, p)
if wsat_assignment:
print("Solution found: ", wsat_assignment)
else:
print("No solution found.")
print("\n")
print("Semi-greedy: ")
semi_greedy_assignment = semi_greedy(problem[:],
maxTries, maxFlips, k)
if semi_greedy_assignment:
print("Solution found: ", semi_greedy_assignment)
else:
print("No solution found.")
print("\n")
input()
Total Contact Hours 20
Guest lecture / Expert sessions:
Sl.No Name of Resource Person Module/Topics Total Hours
1 Prof. Soubhagya Ranjan Mallick 1,2,3,4,5 20
Copyright: The content provided by the faculty in the class is copyrighted. Students are instructed not to distribute
or share content used during courses with external entities.
Disclaimer :The Syllabus and the Course Outline is indicative of the body of knowledge a student should possess.
It does not anyway be construed as a to be covered in class in as-is condition. Faculty may add, delete and modify
content based on updated information or context.