0% found this document useful (0 votes)
5 views

DAA LAB modified

The document outlines various algorithms including non-recursive and recursive methods for finding maximum elements and factorials, respectively. It also covers Strassen's matrix multiplication, topological sorting, heap sort, and the coin change problem, detailing their algorithms, programs, and time complexities. Each exercise demonstrates different algorithmic techniques such as divide and conquer, decrease and conquer, and dynamic programming.

Uploaded by

sudararam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DAA LAB modified

The document outlines various algorithms including non-recursive and recursive methods for finding maximum elements and factorials, respectively. It also covers Strassen's matrix multiplication, topological sorting, heap sort, and the coin change problem, detailing their algorithms, programs, and time complexities. Each exercise demonstrates different algorithmic techniques such as divide and conquer, decrease and conquer, and dynamic programming.

Uploaded by

sudararam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

EXERCISE 1: IMPLEMENT RECURSIVE AND NON-RECURSIVE

ALGORITHMS AND STUDY THE ORDER OF GROWTH FROM log2n


TO n!.

NON - RECURSIVE ALGORITHM :


AIM:To find the maximum element in an array.
ALGORITHM :
1. Get the array A of elements as input.
2. Consider the first element as the maximum
element.
3. Iterate the following:
maxval=A[0]
for i=1 to n-1 do
a. if A[i]>maxval:
i. maxval=A[i]
b. return maxval
PROGRAM:
a = [10, 89, 9, 56, 4, 80, 8]
max_element = a[0]
for i in range(len(a)):
if a[i] > max_element:
max_element = a[i]
print (max_element)

OUTPUT :
89
Time complexity : O(N)
Space complexity : O(1)
RECURSIVE ALGORITHM :
AIM : To find the factorial of a given number.
ALGORITHM:
1. Get an integer x as input.
2. Define a function F(x) to return factorial of a
number.
3. If the input is 0 then return 1 else return F(x-1)*x.

PROGRAM:
def factorial(x):
if x == 0:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))

OUTPUT :
The factorial of 3 is 6.
Time complexity : O(N)
Space complexity : O(N)

EXERCISE 2: DIVIDE AND CONQUER - STRASSEN’S MATRIX


MULTIPLICATION

AIM :To find the matrix multiplication of the given


matrices using Strassen’s multiplication method.
ALGORITHM :
1. Get two nxn matrices as input from the user and
name them as A and B.
2. Divide the matrices into order of n/2 x n/2.
3. Apply the formulae below to find the final matrix
C.
m1=(A11+A22)*(B11+B22)
m2 = (A21 + A22) * B11
m3 = A11 * (B12 - B22)
m4 = A22 * (B21 - B11)
m5 = (A11 + A12) * B22
m6 = (A21 - A11) * (B11 + B12)
m7 = (B21 + B22) * (A12 - A22)

C11 = m1 + m4 – m5 + m6
C12 = m3 + m5
C21 = m2 + m4
C22 = m1 + m4 – m2 + m6

4. The matrix C with matrix elements C11, C12, C21 ,


C22 is the resultant matrix.

PROGRAM :
import numpy as np

def split(matrix):
row, col = matrix.shape
row2, col2 = row//2, col//2
return matrix[:row2, :col2], matrix[:row2, col2:],
matrix[row2:, :col2], matrix[row2:, col2:]
def strassen(x, y):
if len(x) == 1:
return x * y
a, b, c, d = split(x)
e, f, g, h = split(y)
p1 = strassen(a, f - h)
p2 = strassen(a + b, h)
p3 = strassen(c + d, e)
p4 = strassen(d, g - e)
p5 = strassen(a + d, e + h)
p6 = strassen(b - d, g + h)
p7 = strassen(a - c, e + f)
c11 = p5 + p4 - p2 + p6
c12 = p1 + p2
c21 = p3 + p4
c22 = p1 + p5 - p3 - p7
c = np.vstack((np.hstack((c11, c12)),
np.hstack((c21, c22))))
return c

OUTPUT :
Time complexity : T(n) = 7 T(n/2) + O(n2)

EXERCISE 3 : DECREASE AND CONQUER –


TOPOLOGICAL SORTING
AIM : To find the topological ordering of the given
directed acyclic graph by source removal method.
ALGORITHM :
1. Identify the node with no incoming edges.
2. Add the node to the output ordering.
3. Remove the node and it’s outgoing edges from the
graph.
4. Repeat the above steps until all the nodes are
removed from the graph and added to the output.
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSortUtil(self,v,visited,stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:

self.topologicalSortUtil(i,visited,stack)
stack.insert(0,v)
def topologicalSort(self):
visited = [False]*self.V
stack =[]
for i in range(self.V):
if visited[i] == False:

self.topologicalSortUtil(i,visited,stack)
print (stack)

g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print ("Following is a Topological Sort of the given
graph")
g.topologicalSort()

OUTPUT :
Following is a Topological Sort of the given graph
[5, 4, 2, 3, 1, 0]
Time complexity :O(|V| + |E| )
where V – vertices & E – edges

EXERCISE 4 : TRANSFORM AND CONQUER – HEAP SORT


AIM : To find the heap sort for the given list of
elements.
ALGORITHM :
1. Build a heap with the given list of elements.
2. After creation of the heap, remove the root
element of the heap by repeatedly shifting it to the
end of the heap and array and then store the heap
structure with the remaining elements.
3. Repeat the steps above until all the elements are
sorted.

PROGRAM :
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
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, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
(arr[i], arr[0]) = (arr[0], arr[i])
heapify(arr, i, 0)
arr = [12, 11, 13, 5, 6, 7, ]
heapSort(arr)
n = len(arr)
print('Sorted array is')
for i in range(n):
print(arr[i])
OUTPUT :
Sorted array is
5
6
7
11
12
13
Time Complexity: O(n*log(n))

EXERCISE 5 : DYNAMIC PROGRAMMING – COIN CHANGE


PROBLEM, WARSHALL’S AND FLOYD’S ALGORITHM,
KNAPSACK PROBLEM.

COIN CHANGE PROBLEM :


AIM : To write a python program to give change for
amount ‘n’ using minimum number of coins of
denominations.
ALGORITHM :

1. Initialize a new array for A of length n+1, where n is


the number of different coin changes you want to
find.
2. Because there is only one way to give change for 0
dollars, set A[0] to 1.
3. Iterate through the array for each coin change
available and add the value of A[index-coins[i]] to
A[index] for indexes ranging from '1' to 'n'.
4. Return the value of A[n].
5. The size of the A is equal to (number of coins +1) *
(Sum +1).
6. The first column value is one because there is only
one way to change if the total amount is 0.
7. Row: The total number of coins. The fact that the
first-row index is 0 indicates that no coin is
available. If the value index in the second row is 1,
only the first coin is available. Similarly, if the value
index in the third row is 2, it means that the first two
coins are available to add to the total amount, and so
on. The row index represents the index of the coin in
the coins array, not the coin value.
8. Column: Total amount (sum). Because the first-
column index is 0, the sum value is 0. The second
column index is 1, so the sum of the coins should be
1. Similarly, the third column value is 2, so a change
of 2 is required, and so on.
9. As a result, each table field stores the solution to a
subproblem. For example, A[2][3]=2 indicates two
ways to compute the sum of three using the first two
coins 1,2.
10. The final outcome will be calculated by the values
in the last column and row.
11. In this case, you must loop through all of the
indexes in the memo table (except the first row and
column) and use previously-stored solutions to the
subproblems.
12. If the coin value is greater than the ASum, the
coin is ignored, i.e. ATable[i][j] = ATable[i-1][j].
13. If the coin value is less than the ASum, you can
consider it, i.e. ATable[i][j]=ATable[i-1].[ASum]
+ATable[i][j-coins[i-1]].

PROGRAM :
def count(S, m, n):
table = [[0 for x in range(m)] for x in range(n+1)]
for i in range(m):
table[0][i] = 1
for i in range(1, n+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0
table[i][j] = x + y
return table[n][m-1]
arr = [1, 3, 2, 4]
m = len(arr)
n=5
print(“Number of coins:”,end=””)
print(count(arr, m, n))

OUTPUT :
Number of coins:6
Time complexity : O(nxm)
where n - no. of subproblem & m - weight

You might also like