Professional Documents
Culture Documents
Practical 1
Aim: Implementation and Time analysis of sorting algorithms. Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort.
Bubble sort:
def bubblesort(elements):
swapped = False
for i in range(n):
swapped = True
return
print(elements)
bubblesort(elements)
print(elements)
Output:
1
Analysis & Design Of Algorithms
Selection sort:
def selectionSort(array, size):
min_index = ind
for j in range(ind + 1, size):
Output:
The array after sorting in Ascending Order by selection sort is:
[-202, -97, -9, -2, 0, 11, 45, 88, 747]
2
Analysis & Design Of Algorithms
Insertion sort:
def insertionSort(arr):
key = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
insertionSort(arr)
lst = []
print("Sorted array is : ")
for i in range(len(arr)):
lst.append(arr[i])
print(lst)
Output:
3
Analysis & Design Of Algorithms
Merge sort:
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
L[i] = arr[l + i]
R[j] = arr[m + 1 + j]
i=0
j=0
k=l
while i < n1 and j < n2:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
4
Analysis & Design Of Algorithms
k += 1
if l < r:
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
n = len(arr)
for i in range(n):
mergeSort(arr, 0, n-1)
for i in range(n):
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
5
Analysis & Design Of Algorithms
Quicksort Sort
def partition(array, low, high):
pivot = array[high]
i = low - 1
i=i+1
return i + 1
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print(data)
Output:
Unsorted Array
[1, 7, 4, 1, 10, 9, -2]
Sorted Array in Ascending Order:
[-2, 1, 1, 4, 7, 9, 10]
6
Analysis & Design Of Algorithms
Time Complexity:
7
Analysis & Design Of Algorithms
Practical-2
Aim:Implementation and Time analysis of linear and binary search
algorithm.
Linear search:
def linear_Search(list1, n, key):
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output:
Binary Search:
def binary_search(list1, n):
low = 0
8
Analysis & Design Of Algorithms
high = len(list1) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
elif list1[mid] > n:
high = mid - 1
else:
return mid
return -1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
Output:
9
Analysis & Design Of Algorithms
Time complexity:
10
Analysis & Design Of Algorithms
Practical-3
Aim:Implementation of max-heap sort algorithm.
def heapify(arr, N, i):
largest = l
largest = r
if largest != i:
heapify(arr, N, largest)
def heapSort(arr):
N = len(arr)
heapify(arr, N, i)
heapify(arr, i, 0)
if __name__ == '__main__':
heapSort(arr)
N = len(arr)
print("Sorted array is")
for i in range(N):
11
Analysis & Design Of Algorithms
Output:
Sorted array is
5 6 7 11 12 13
Time Complexity:
12
Analysis & Design Of Algorithms
Practical-4
Aim:Implementation and Time analysis of factorial program using
iterative and recursive method
recursive method:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Output:
Iterative method:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
13
Analysis & Design Of Algorithms
num = 7
result = factorial(num)
Output:
Time Complexity:
14
Analysis & Design Of Algorithms
Practical-5
AIM:Implementation of a knapsack problem using dynamic programming
if i == 0 or w == 0:
K[i][w] = 0
else:
K[i][w] = K[i-1][w]
return K[n][W]
W = 50
n = len(val)
Output:
220
15
Analysis & Design Of Algorithms
Time Complexity:
16
Analysis & Design Of Algorithms
Practical-6
Aim:Implementation of chain matrix multiplication using dynamic
programming
import sys
if i == j:
return 0
_min = sys.maxsize
+ MatrixChainOrder(p, k + 1, j)
_min = count;
return _min;
n = len(arr);
MatrixChainOrder(arr, 1, n-1));
OutPut:
17
Analysis & Design Of Algorithms
Time Complexity:
18
Analysis & Design Of Algorithms
Practical-7
Aim:Implementation of making a change problem using dynamic
programming
for i in range(m):
table[0][i] = 1
Output:
4
Time Complexity:
19
Analysis & Design Of Algorithms
Practical-8
Aim:Implementation of a knapsack problem using greedy algorithm
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
finalvalue = 0.0
for item in arr:
if item.weight <= W:
W -= item.weight
finalvalue += item.value
else:
finalvalue += item.value * W / item.weight
break
return finalvalue
if __name__ == "__main__":
W = 50
arr = [Item(60, 10), Item(100, 20), Item(120, 30)]
max_val = fractionalKnapsack(W, arr)
print(max_val)
20
Analysis & Design Of Algorithms
Output:
240.0
Time Complexity:
21
Analysis & Design Of Algorithms
Practical-9
Aim:Implementation of Graph and Searching (DFS and BFS).
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
22
Analysis & Design Of Algorithms
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
Output:
23
Analysis & Design Of Algorithms
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)
24
Analysis & Design Of Algorithms
Output:
Time Complexity:
25
Analysis & Design Of Algorithms
Practical-10
Aim:Implement prim’s algorithm.
We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s
algorithm, Prim’s algorithm is also a Greedy algorithm. Prim’s algorithm always starts with a
single node and it moves through several adjacent nodes, in order to explore all of the
connected edges along the way.
import sys
class Graph():
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
def primMST(self):
26
Analysis & Design Of Algorithms
self.printMST(parent)
if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST()
27
Analysis & Design Of Algorithms
Output:
Time Complexity:
28
Analysis & Design Of Algorithms
Practical-11
Aim:Implement kruskal’s algorithm.
class Graph:
else:
parent[y] = x
rank[x] += 1
def KruskalMST(self):
29
Analysis & Design Of Algorithms
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)
if __name__ == '__main__':
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
30
Analysis & Design Of Algorithms
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
Output:
Time Complexity:
31
Analysis & Design Of Algorithms
Practical-12
Aim:Implement LCS problem.
def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
X = "AGGTAB"
Y = "GXTXAYB"
print ("Length of LCS is ", lcs(X , Y, len(X), len(Y)) )
Output:
Time Complexity:
32