Lab Manual 22CS303 DAA (1)
Lab Manual 22CS303 DAA (1)
ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206
22CS303
DESIGN AND ANALYSIS OF ALGORITHMS
(LAB INTEGRATED)
LAB MANUAL
R2022
ODD SEMESTER
22CS303
DESIGN AND ANALYSIS OF ALGORITHMS
(LAB INTEGRATED)
LAB MANUAL
R2022
Prepared by
Dr. K.SUDHARSON,
Associate Professor/AIML
Mr.N.SATHISH KUMAR
Assistant Professor/AIML
R.M.D. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206
Vision
To become an internationally recognized destination by producing professionals in Artificial Intelligence and
Machine Learning through excellence in education and move the society in interesting and innovative directions.
.Mission
1. To impart premier quality, skill-based and value-based education to the students in the field of Artificial
Intelligence and Machine Learning
2. To transform the students into technically competent professionals and help them to imbibe the creative
spirit.
3. To identify industrial requirements and enhance the students’ niche expertise.
4. To build an ecosystem that will have an ethical impact on the society.
Programme Educational Objectives
PEO 1: Work effectively in inter-disciplinary field with the knowledge of Artificial Intelligence and Machine
Learning to develop appropriate solutions to real-world problems.
PEO 2: Excel in professional career and pursue higher education in the field of Artificial Intelligence and
Machine Learning.
PEO 3: Apply their knowledge to the technological revolution through life-long learning.
PEO 4: Excel as socially committed engineers or entrepreneurs with high ethical and moral values
Programme Specific Outcome
PSO 1: Apply fundamental concepts of Artificial Intelligence and Data Science to solve technical problems
PSO 2: Utilize Artificial Intelligence and Data Science tools to provide innovative business solutions.
PSO 3: Implement the domain knowledge to achieve successful career as an employee, entrepreneur and an
engineering professional
R.M.D. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206
DEPARTMENT OF AIRTIFICIAL INTELLIGENCE AND MACHINE
LEARNING
OBJECTIVES:
Critically analyse the efficiency of alternative algorithmic solutions for the same problem
Illustrate brute force and divide and conquer design techniques.
Explain dynamic programming for solving various problems.
Apply greedy technique and iterative improvement technique to solve optimization problems
Examine the limitations of algorithmic power and handling it in different problems.
LIST OF EXERCISES:
Date :
Exercise Number :1
Aim:
To write a program to implement the recursive algorithm analysis – factorial of an integer
Algorithm:
Initialize m=0
If n=1 return
else
print m
Pseudocode:
Initialize m to 0
Algorithm f(n)
{
if n=1
return 1
else
m++
return f(n-1) * n
print f(n),m
}
Input:
5
Output:
120
m=4
Result:
The Program for implement the recursive algorithm analysis is successfully executed.
Date :
Exercise Number :2
Aim:
To write a program to implement the non-recursive algorithm analysis
Algorithm:
Initialize a=0
Increment a counter inside the innermost loop and print it
Pseudocode:
Algorithm maxElement(A[0..n-1])
{
count=0
max=A[0]
for i = 1 to n-1
if (A[i] > max)
count++
max=A[i]
print count, max
}
Input:
A[]={4,1,9,23,7,3}
Output:
Maximum=23
count=6
Result:
The Program for implement the non-recursive algorithm analysis is successfully executed.
Date :
Exercise Number :3
Aim:
To write a program to search an element in an array using binary search
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.
If the key is smaller than the middle element, then the left side is used for next search.
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.
Pseudocode:
Input:
A[]={8,15,26,42,55,68,72,94,111}, K=94
Output:
Position of the Key is 7.
Result:
The Program for binary search is successfully executed.
Date :
Exercise Number :4
Title : Write a program to sort the elements using merge sort and find time complexity
Aim:
To write a program to sort the elements using merge sort.
Algorithm:
Divide the elements in to two sub-arrays until in each array one element is available.
Sort the elements in two sorted sub-arrays
Take one element from each sub-array and compare.
Smallest element is moved to result array.
Repeat the process until all the elements from one array copied in to result
Copy the remaining elements from the other array in to result array.
Pseudocode:
Mergesort(A[0..n − 1])
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)
Input:
8,3,2,9,7,1,5,4
Output:
1,2,3,4,5,7,8,9
Result:
The Program for merge sort is successfully executed.
Date :
Exercise Number :5
Title : Write a program to sort the elements using quick sort and find time complexity
Aim:
To write a program to sort the elements using quick sort.
Algorithm:
Assume the first element in the array is the partition element.
Find a suitable position for the partition element such that all the elements to the left of
partition element are lesser and to the right of partition element are greater.
Based on the position of the partition element, the array is divided into two sub-arrays.
Repeat the above process separately for left array and right array until all the elements
are sorted
Pseudocode:
Quicksort(A[l..r])
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s − 1])
Quicksort(A[s + 1..r])
Partition(A[l..r])
p←A[l]
i ←l;
j ←r + 1
repeat
repeat
i ←i + 1
until A[i]≥ p
repeat
j ←j − 1
until A[j ]≤ p
swap(A[i], A[j ])
until i ≥ j
swap(A[i], A[j ])
swap(A[l], A[j ])
return j
Input:
8,3,2,9,7,1,5,4
Output:
1,2,3,4,5,7,8,9
Result:
The Program for quick sort is successfully executed.
Date :
Exercise Number :6
Aim:
To write a program to sort the elements using heap sort.
Algorithm:
Construct the binary heap for the given array of elements
Swap the root element with last element in the heap.
Delete and move the element in the last node to an array
Check for the heap property
Repeat the above process until all the elements from the heap are moved to the array
The array contains the sorted elements.
Pseudocode:
HeapBottomUp(H[1..n])
for i ←_n/2_ downto 1 do
k←i; v←H[k]
j ←2 ∗ k
if j <n
if H[j ]<H[j + 1] j ←j + 1
if v ≥ H[j ]
heap←true
else
H[k]←H[j ];
k←j
H[k]←v
Input:
8,3,2,9,7,1,5,4
Output:
1,2,3,4,5,7,8,9
Result:
The Program for heap sort is successfully executed.
Date :
Exercise Number :7
Title : Write a program to find all pair shortest path using Floyd’s algorithm.
Aim:
To write a program to find all pair shortest path using Floyd’s algorithm.
Algorithm:
Create a matrix A0 of dimension n*n where n is the number of vertices. The row and the column
are indexed as i and j respectively. i and j are the vertices of the graph. Each cell A[i][j] is filled
with the distance from the ith vertex to the jth vertex. If there is no path from ith vertex
to jth vertex, the cell is left as infinity.
Create a matrix A1 using matrix A0. The elements in the first column and the first row are left as
they are.
The remaining cells are filled in the following way.
Let k be the intermediate vertex in the shortest path from source to destination. In this step, k is
the first vertex. A[i][j] is filled with (A[i][k] + A[k][j]) if (A[i][j] > A[i][k] + A[k][j]).
Similarly, A2 is created using A1. The elements in the second column and the second row are left
as they are. This process will be repeated until An matrix is created.
Pseudocode:
Floyd(W[1..n, 1..n])
D ←W
for k←1 to n do
for i ←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
Input:
Output:
Result:
The Program for finding all pair shortest path using Floyd’s algorithm is successfully
executed.
Date :
Exercise Number :8
Title : Write a program to find optimal binary search tree for a given list of keys.
Aim:
To write a program to find optimal binary search tree for a given list of keys.
Algorithm:
Pseudocode:
OptimalBST(P [1..n])
for i ←1 to n do
C[i, i − 1]←0
C[i, i]←P[i]
R[i, i]←i
C[n + 1, n]←0
for d ←1 to n − 1 do //diagonal count
for i ←1 to n − d do
j ←i + d
minval←∞
for k←i to j do
if C[i, k − 1]+ C[k + 1, j]< minval
minval←C[i, k − 1]+C[k + 1, j];
kmin←k
R[i, j ]←kmin
sum←P[i];
for s ←i + 1 to j do
sum←sum + P[s]
C[i, j ]←minval + sum
return C[1, n], R
Input:
keys = [10, 12, 20];
freq = [34, 8, 50];
Output:
Cost of OBST is 142
Result:
The Program for finding optimal Binary Search Tree is successfully executed.
Date :
Exercise Number :9
Title : Write a program to multi-stage graph to find shortest path using backward and
forward approach.
Aim:
To write a program to multi-stage graph to find shortest path using backward and forward
approach.
Algorithm:
Set d(t) = 0 and d(v) = ∞ for all other vertices v in G.
For i = k-1 to 1:
Fgraph(G, k, n, p)
{
cost [n] = 0.0;
for j = n - 1 to 1 step – 1 do
cost [j] = c [j, r] + cost[r];
d [j] = r:
p [1] = 1;
p [k] = n;
for j = 2 to k - 1 do
p [j] = d [p [j -1]];
}
Input:
{INF, 1, 2, 5, INF, INF, INF, INF},
INF, INF, INF, INF, 4, 11, INF, INF},
{INF, INF, INF, INF, 9, 5, 16, INF},
{INF, INF, INF, INF, INF, INF, 2, INF},
{INF, INF, INF, INF, INF, INF, INF, 18},
{INF, INF, INF, INF, INF, INF, INF, 13},
{INF, INF, INF, INF, INF, INF, INF, 2},
{INF, INF, INF, INF, INF, INF, INF, INF}};
Output:
Cost of Shortest Path is 9
Result:
The Program for finding shortest path in multi-stage graph using forward and
backward approach is successfully executed.
Date :
Exercise Number : 10
Aim:
Pseudocode:
Algorithm: LCS-Length-Table-Formulation (X, Y):
m := length(X)
n := length(Y)
for i = 1 to m do
C[i, 0] := 0
for j = 1 to n do
C[0, j] := 0
for i = 1 to m do
for j = 1 to n do
if xi = yj
C[i, j] := C[i - 1, j - 1] + 1
B[i, j] := ‘D’
else
if C[i -1, j] ≥ C[i, j -1]
C[i, j] := C[i - 1, j]
B[i, j] := ‘U’
else
C[i, j] := C[i, j - 1]
B[i, j] := ‘L’
return C and B
Input:
X = BACDB and Y = BDCB
Output:
BCB
Result:
The Program for finding longest common subsequence is successfully executed.
Date :
Exercise Number : 11
Title : Write a program to find minimum spanning tree using Prim’s algorithm
Aim:
Algorithm:
Step1: 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
Pseudocode:
ALGORITHM Prim(G)
ET←Φ
for i ←1 to |V| − 1 do
find a minimum-weight edge e ∗ = (v∗, u∗) among all the edges (v, u) such that v is in V T and u is
in V– VT
VT←VT∪ {u*}
ET←ET∪ {e*}
return ET
Input:
{ { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
Output:
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
Result:
The Program for finding minimum spanning tree using Prim’s algorithm is successfully
executed.
Date :
Exercise Number : 12
Title : Write a program to find minimum spanning tree using Kruskal’s algorithm
Aim:
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.
Pseudocode:
ALGORITHM Kruskal(G)
k←0
ET ← Φ; ecounter ← 0
while ecounter < |V| − 1 do
k←k+1
if ET ∪ {eik} is acyclic
ET ← ET ∪ {eik}; ecounter ← ecounter + 1
return ET
Input:
{ { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };
Output:
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
Result:
The Program for finding minimum spanning tree using Kruskal’s algorithm is
successfully executed.
Date :
Exercise Number : 13
Aim:
Algorithm:
1. Start with initial flow as 0.
2. While there exists an augmenting path from the source to the sink:
Find an augmenting path using any path-finding algorithm, such as breadth-first
search or depth-first search.
Determine the amount of flow that can be sent along the augmenting path, which
is the minimum residual capacity along the edges of the path.
Increase the flow along the augmenting path by the determined amount.
3. Return t
he maximum flow.
Pseudocode:
v) ∈ p
while there exists a path p from s to t in the residual network G f such that Cf (u, v)>0 for all edges (u,
Output:
Minimum Flow = 6
Result:
The Program for finding maximum flow is successfully executed.
Date :
Exercise Number : 14
Aim:
Algorithm:
Pseudocode:
Algorithm Sumofsubset (s,k,r)
X[k]=1
if (s+W[k]=m) then write (X[1:k])
else if (s+W[k]+W[k+1]<=m)
then sumofsubset(s+W[k],k+1,r-W[k])
if (s+r-W[k]>=m) and (s+W[k+1]<=m) then
X[k]=0
sumofsubset(s,k+1,r-W[k])
Input:
X[]={1,2,1}, sum=3
Output:
[1,2], [2,1]
Result:
The Program for sum of subset problem is successfully executed.
Date :
Exercise Number : 15
Aim:
Algorithm:
1. Initialize an empty chessboard of size NxN.
2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a queen
in the current column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules of the
problem, backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7 until all possible configurations have been tried.
Pseudocode:
N - Queens (k, n)
{
for i ← 1 to n
do if Place (k, i) then
{
x [k] ← i;
if (k ==n) then
write (x [1....n));
else
N - Queens (k + 1, n);
}
}
Place (k, i)
{
For j ← 1 to k - 1
do if (x [j] = i)
or (Abs x [j]) - i) = (Abs (j - k))
then return false;
return true;
}
Input:
N=4
Output:
(1,2) -> (2,4) -> (3,1) -> (4,3)|
Result:
The Program for N-Queen problem is successfully executed.
Date :
Exercise Number : 16
Title : Write a program to solve the Knapsack problem using branch and bound
technique
Aim:
To write a program to solve the knapsack problem using branch and bound technique.
Algorithm:
1. Sort all items in decreasing order of ratio of value per unit weight so that an upper
bound can be computed using Greedy Approach.
2. Initialize maximum profit, maxProfit = 0
3. Create an empty queue, Q.
4. Create a dummy node of decision tree and enqueue it to Q. Profit and weight of
dummy node are 0.
5. Do following while Q is not empty.
Extract an item from Q. Let the extracted item be u.
Compute profit of next level node. If the profit is more than maxProfit, then update
maxProfit.
Compute bound of next level node. If bound is more than maxProfit, then add next level
node to Q.
Consider the case when next level node is not considered as part of solution and add a node
to queue with level as next, but weight and profit without considering next level nodes.
Pseudocode:
Sort all the items on value/weight ratio
function knapsack(items, max_weight):
best_value = 0
queue = [{items: [], value: 0, weight: 0}]
while queue is not empty:
node = queue.pop()
if node is a leaf node:
update best_value if necessary
else:
for each remaining item:
child = create child node for item
if child is promising:
queue.append(child)
return best_value
function is_promising(node, max_weight, best_value):
if node.weight > max_weight:
return False
if node.value + bound(node.items) < best_value:
return False
return True
function bound(items):
# Calculate an upper bound on the value of the remaining items
value+(W-weight)*(value/weight) of next item
Input:
N=4, W=10
Item w v
1 4 40
2 7 42
3 5 25
4 3 12
Output:
Value = 65
Result:
The Program for Knapsack problem using branch and bound is successfully executed.
Date :
Exercise Number : 17
Title : Write a program to solve the assignment problem using branch and bound
technique
Aim:
To write a program to solve the assignment problem using branch and bound technique.
Algorithm:
1. For each person select the job with minimum cost and add all. This is the lower bound
2. Start with a person assign the minimum cost job and for all other persons choose the one
minimum cost other than assigned. Sum up all the cost.
3. Proceed from the least cost assignment further to assign the job for others. Repeat step 2
until all persons are assigned with one job.
Pseudocode:
/* findMinCost uses Least() and Add() to maintain the
list of live nodes
Input:
Person/Job J1 J2 J3 J4
P1 9 2 7 8
P2 6 4 3 7
P3 5 8 1 8
P4 7 6 9 4
Output:
Cost=13
Result:
The Program for assignment problem using branch and bound is successfully executed.