0% found this document useful (0 votes)
14 views22 pages

ADA - Practical-1 To 5

Uploaded by

RIA PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views22 pages

ADA - Practical-1 To 5

Uploaded by

RIA PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Analysis and Design of Algorithms [3150703] Enrollment No.

-23093107021

Practical-1
1.1 Implementation and Time analysis of sorting algorithms: Bubble sort

CODE:
def bubble_sort(arr):

for n in range(len(arr) - 1, 0, -1):

for i in range(n):
if arr[i] > arr[i + 1]:
swapped = True
arr[i], arr[i + 1] = arr[i + 1], arr[i]

arr = [20,15,85,61,23,99,55]
print("Unsorted list is:")
print(arr)

bubble_sort(arr)

print("Sorted list is:")


print(arr)

OUTPUT:

Worst-Case Time Complexity: O(n²)


Average Time Complexity: O(n²)
Best-Case Time Complexity: O(n).

COED, CKPCET |1
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

1.2 Implementation and Time analysis of sorting algorithms: Selection sort.

CODE:
def selectionSort(array, size):

for ind in range(size):


min_index = ind

for j in range(ind + 1, size):


if array[j] < array[min_index]:
min_index = j
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2,0,12,-10,-55,88,97,-25]
size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)

OUTPUT:

Worst-Case Time Complexity: O(n²)


Average Time Complexity: O(n²)
Best-Case Time Complexity: O(n²).

COED, CKPCET |2
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

1.3 Implementation and Time analysis of sorting algorithms: Insertion sort.

CODE:
def insertionSort(arr):
n = len(arr)
if n <= 1:
return
for i in range(1, n):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = [25,14,41,89,2,75]
print("Unsorted list is:")
print(arr)
insertionSort(arr)
print("Sorted list is:")
print(arr)

OUTPUT:

Worst-Case Time Complexity: O(n²)


Average Time Complexity: O(n²)
Best-Case Time Complexity: O(n).

COED, CKPCET |3
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

1.4 Implementation and Time analysis of factorial program using iterative and
recursive method.

CODE:
def factorial(n):
if (n==1 or n==0):
return 1
else
return (n * factorial(n - 1))
num = 7
print("number : ",num)
print("Factorial : ",factorial(num))

OUTPUT:

Time Complexity: O(n)


Auxiliary Space: O(1)

COED, CKPCET |4
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

Practical-2
2.1 Implementation and Time analysis of Linear search algorithm.

CODE:
def linear_search(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1

arr = [10, 20, 30, 40, 50]


target = 30
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

OUTPUT:

Worst-Case Time Complexity: O(n)


Average Time Complexity: O(n)
Best-Case Time Complexity: O(1).

COED, CKPCET |5
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

2.2 Implementation and Time analysis of Binary search algorithm.

CODE:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [10, 20, 30, 40, 50]
target = 40
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

OUTPUT:

Worst-Case Time Complexity: O(log n)


Average Time Complexity: O(log n)
Best-Case Time Complexity: O(1).

COED, CKPCET |6
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

2.3 Implementation and Time analysis of Merge sort

CODE:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
return arr
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted array: ")
print(arr)

COED, CKPCET |7
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

sorted_arr = merge_sort(arr)
print("Sorted array is:")
print(sorted_arr)

OUTPUT:

Worst-Case Time Complexity: O(n log n)


Average Time Complexity: O(n log n)
Best-Case Time Complexity: O(n log n).

COED, CKPCET |8
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

2.4 Implementation and Time analysis of Quick sort

CODE:
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
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 quick_sort(left) + middle + quick_sort(right)

arr = [64, 34, 25, 12, 22, 11, 90]


print("Unsorted array: ")
print(arr)
sorted_arr = quick_sort(arr)
print("Sorted array is:")
print(sorted_arr)

OUTPUT:

Worst-Case Time Complexity: O(n²)


Average Time Complexity: O(n log n)
Best-Case Time Complexity: O(n log n).

COED, CKPCET |9
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

2.5 Implementation of Max-Heap sort algorithm

CODE:
def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)

def build_max_heap(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
def heap_sort(arr):
n = len(arr)
build_max_heap(arr)
for i in range(n - 1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted array: ")
print(arr)
heap_sort(arr)
print("Sorted array is:")
print(sorted_arr)

COED, CKPCET | 10
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

OUTPUT:

Building Max-Heap Time Complexity: O(n)


Heap Sort Time Complexity: O(n log⁡ n)
Overall Time Complexity: O(n log⁡ n)

COED, CKPCET | 11
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

Practical-3
3.1 Implementation of a knapsack problem using dynamic programming.

CODE:
def knapsack(weights, values, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]

# Build the dp array


for i in range(1, n + 1):
for w in range(capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1])
else:
dp[i][w] = dp[i - 1][w]

return dp[n][capacity]

weights = [1, 2, 3]
values = [10, 15, 40]
capacity = 6
max_value = knapsack(weights, values, capacity)
print(f"Maximum value in the knapsack: {max_value}")

OUTPUT:

COED, CKPCET | 12
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.2 Implementation of chain matrix multiplication using dynamic programming.

CODE:
def matrix_chain_order(dimensions):
n = len(dimensions) - 1
m = [[0 for _ in range(n)] for _ in range(n)]

# l is the chain length


for l in range(2, n + 1): # l = 2 to n
for i in range(n - l + 1):
j=i+l-1
m[i][j] = float('inf')
for k in range(i, j):
q = m[i][k] + m[k + 1][j] + dimensions[i] * dimensions[k + 1] * dimensions[j + 1]
if q < m[i][j]:
m[i][j] = q

return m[0][n - 1]

dimensions = [10, 20, 30, 40, 30]


min_cost = matrix_chain_order(dimensions)
print(f"Minimum number of multiplications: {min_cost}")

OUTPUT:

COED, CKPCET | 13
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.3 Implementation of making a change problem using dynamic programming

CODE:
def coin_change(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)

return dp[amount] if dp[amount] != float('inf') else -1

coins = [1, 2, 5]
amount = 11
min_coins = coin_change(coins, amount)
print(f"Minimum number of coins needed: {min_coins}")

OUTPUT:

COED, CKPCET | 14
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.4 Implement LCS problem.

CODE:
def lcs(seq1, seq2):
m = len(seq1)
n = len(seq2)

dp = [[0] * (n + 1) for _ in range(m + 1)]

for i in range(1, m + 1):


for j in range(1, n + 1):
if seq1[i - 1] == seq2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

return dp[m][n]

seq1 = "AGGTAB"
seq2 = "GXTXAYB"
lcs_length = lcs(seq1, seq2)
print(f"Length of Longest Common Subsequence: {lcs_length}")

OUTPUT:

COED, CKPCET | 15
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.5 Implementation of a Knapsack problem using greedy algorithm.

CODE:
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
self.ratio = value / weight

def fractional_knapsack(capacity, items):


items.sort(key=lambda item: item.ratio, reverse=True)

total_value = 0.0
for item in items:
if capacity == 0:
break
if item.weight <= capacity:
capacity -= item.weight
total_value += item.value
else:
total_value += item.ratio * capacity
capacity = 0

return total_value

items = [Item(60, 10), Item(100, 20), Item(120, 30)]


capacity = 50
max_value = fractional_knapsack(capacity, items)
print(f"Maximum value in the knapsack: {max_value:.2f}")

OUTPUT:

COED, CKPCET | 16
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.6 Implement Prim’s algorithm.

CODE:
import heapq
def prim(graph, start):
mst = []
visited = set()
min_heap = [(0, start, None)]

while min_heap:
weight, current, prev = heapq.heappop(min_heap)

if current not in visited:


visited.add(current)
if prev is not None:
mst.append((prev, current, weight))

for neighbor, edge_weight in graph[current]:


if neighbor not in visited:
heapq.heappush(min_heap, (edge_weight, neighbor, current))

return mst

graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)],
}

mst = prim(graph, 'A')


print("Edges in the Minimum Spanning Tree:")
for edge in mst:
print(f"{edge[0]} -- {edge[1]} with weight {edge[2]}")

OUTPUT:

COED, CKPCET | 17
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

3.7 Implement Kruskal’s algorithm.

CODE:
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.rank = [1] * size

def find(self, u):


if self.parent[u] != u:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]

def union(self, u, v):


rootU = self.find(u)
rootV = self.find(v)

if rootU != rootV:
if self.rank[rootU] > self.rank[rootV]:
self.parent[rootV] = rootU
elif self.rank[rootU] < self.rank[rootV]:
self.parent[rootU] = rootV
else:
self.parent[rootV] = rootU
self.rank[rootU] += 1
return True
return False

def kruskal(vertices, edges):


edges.sort(key=lambda x: x[2])
uf = UnionFind(len(vertices))
mst = []

for u, v, weight in edges:


if uf.union(u, v):
mst.append((u, v, weight))

return mst

vertices = [0, 1, 2, 3]
edges = [
(0, 1, 10),
(0, 2, 6),
(0, 3, 5),

COED, CKPCET | 18
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

(1, 3, 15),
(2, 3, 4)
]

mst = kruskal(vertices, edges)


print("Edges in the Minimum Spanning Tree:")
for edge in mst:
print(f"{edge[0]} -- {edge[1]} with weight {edge[2]}")

OUTPUT:

COED, CKPCET | 19
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

Practical-4
4.1 Implementation of Graph and Searching : Breadth First Search.

CODE:
from collections import deque

class Graph:
def __init__(self):
self.adjacency_list = {}

def add_edge(self, u, v):


if u not in self.adjacency_list:
self.adjacency_list[u] = []
if v not in self.adjacency_list:
self.adjacency_list[v] = []
self.adjacency_list[u].append(v)
self.adjacency_list[v].append(u)

def bfs(self, start):


visited = set()
queue = deque([start])
bfs_order = []

while queue:
current = queue.popleft()
if current not in visited:
visited.add(current)
bfs_order.append(current)
for neighbor in self.adjacency_list.get(current, []):
if neighbor not in visited:
queue.append(neighbor)

return bfs_order

graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)

bfs_result = graph.bfs(0)
print("BFS Traversal Order:", bfs_result)

COED, CKPCET | 20
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

4.2 Implementation of Graph and Searching : Depth First Search

CODE:
class Graph:
def __init__(self):
self.adjacency_list = {}

def add_edge(self, u, v):


if u not in self.adjacency_list:
self.adjacency_list[u] = []
if v not in self.adjacency_list:
self.adjacency_list[v] = []
self.adjacency_list[u].append(v)
self.adjacency_list[v].append(u) # For undirected graph

def dfs(self, start, visited=None):


if visited is None:
visited = set() # To keep track of visited nodes

visited.add(start)
dfs_order = [start] # Record the order of traversal

for neighbor in self.adjacency_list.get(start, []):


if neighbor not in visited:
dfs_order.extend(self.dfs(neighbor, visited)) # Recursive DFS call

return dfs_order

# Example usage
graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)

dfs_result = graph.dfs(0)
print("DFS Traversal Order:", dfs_result)

COED, CKPCET | 21
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021

Practical-5
5.1 Implementation of Rabin-Karp Algorithm for Pattern Searching.

CODE:
def rabin_karp(text, pattern):
d = 256
q = 101

M = len(pattern)
N = len(text)
p=0
t=0
h=1

for i in range(M - 1):


h = (h * d) % q

for i in range(M):
p = (d * p + ord(pattern[i])) % q
t = (d * t + ord(text[i])) % q

for i in range(N - M + 1):


if p == t:
if text[i:i + M] == pattern:
print(f"Pattern found at index {i}")

if i < N - M:
t = (d * (t - ord(text[i]) * h) + ord(text[i + M])) % q
if t < 0:
t += q

text = "Ria R. Patel"


pattern = "R."
rabin_karp(text, pattern)

OUTPUT:

COED, CKPCET | 22

You might also like