ADA - Practical-1 To 5
ADA - Practical-1 To 5
-23093107021
Practical-1
1.1 Implementation and Time analysis of sorting algorithms: Bubble sort
CODE:
def bubble_sort(arr):
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)
OUTPUT:
COED, CKPCET |1
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
CODE:
def selectionSort(array, size):
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:
COED, CKPCET |2
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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:
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:
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
OUTPUT:
COED, CKPCET |5
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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:
COED, CKPCET |6
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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:
COED, CKPCET |8
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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)
OUTPUT:
COED, CKPCET |9
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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:
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)]
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
CODE:
def matrix_chain_order(dimensions):
n = len(dimensions) - 1
m = [[0 for _ in range(n)] for _ in range(n)]
return m[0][n - 1]
OUTPUT:
COED, CKPCET | 13
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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)
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
CODE:
def lcs(seq1, seq2):
m = len(seq1)
n = len(seq2)
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
CODE:
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
self.ratio = value / weight
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
OUTPUT:
COED, CKPCET | 16
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
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)
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)],
}
OUTPUT:
COED, CKPCET | 17
Analysis and Design of Algorithms [3150703] Enrollment No.-23093107021
CODE:
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.rank = [1] * size
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
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)
]
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 = {}
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
CODE:
class Graph:
def __init__(self):
self.adjacency_list = {}
visited.add(start)
dfs_order = [start] # Record the order of traversal
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):
p = (d * p + ord(pattern[i])) % q
t = (d * t + ord(text[i])) % q
if i < N - M:
t = (d * (t - ord(text[i]) * h) + ord(text[i + M])) % q
if t < 0:
t += q
OUTPUT:
COED, CKPCET | 22