Ada Manual
Ada Manual
values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.
import timeit
Array.append(ele)
# Linear Searching
for x in Array:
if x == key:
return True
return False
# Main Block()
if __name__ == "__main__": # Ensures the following code runs only when the script is executed
directly
N = []
CPU = []
Array = []
key = int(input("Enter key to search: ")) #changed the input line to identify the key
start = timeit.default_timer()
s = linear_search(Array, key)
N.append(n)
print("N CPU")
print(N[t], CPU[t])
# Plotting Graph
plt.plot(N, CPU)
plt.show()
OUTPUT:
-----> TRAIL NO : 1
Arr[1]: 23
Arr[2]: 34
Arr[3]: 45
Arr[4]: 67
-----> TRAIL NO : 2
Arr[1]: 34
Arr[2]: 56
Arr[3]: 78
Arr[4]: 90
N CPU
4 86.9
4 124.2
PROGRAM 2: write a program to implement Binary search algorithm. Repeat the experiment for different
values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.
import timeit
Array.append(ele)
# Binary Searching
low = 0
high = len(Array) - 1
if Array[mid] == key:
return True
else:
return False
# Main Block()
if __name__ == "__main__":
N = []
CPU = []
Input(Array, n)
print("Array:", Array)
start = timeit.default_timer()
s = binary_search(Array, key)
N.append(n)
print("N CPU")
print(N[t], CPU[t])
# Plotting Graph
plt.plot(N, CPU)
plt.show()
OUTPUT:
-----> TRAIL NO : 1
Enter number of elements : 6
Arr[1]: 10
Arr[2]: 20
Arr[3]: 30
Arr[4]: 40
Arr[5]: 50
Arr[6]: 60
Enter key : 45
-----> TRAIL NO : 2
Arr[1]: 45
Arr[2]: 67
Arr[3]: 89
Arr[4]: 54
Arr[5]: 56
Enter key : 89
N CPU
6 92.0
5 102.6
PROGRAM 3: write a program to solve towers of Hanoi problem and execute it for different number of
disks.
if n == 1:
return
# Main Block
OUTPUT:
PROGRAM 4: write a program to sort a given set of number using selection sort algorithm. Repeat the
experiment for different values of n, the number of elements can be read from a file or can be generated
using the random number generator
import timeit
import random
Array.append(ele)
# Selection Sort
min_index = ind
min_index = j
# Main Block()
if __name__ == "__main__":
N = []
CPU = []
Array = []
Input(Array, n)
start = timeit.default_timer()
selectionSort(Array, n)
print(Array)
N.append(n)
print("N CPU")
print(N[t], CPU[t])
# Plotting Graph
plt.plot(N, CPU)
OUTPUT:
-----> TRAIL NO : 1
Sorted Array :
-----> TRAIL NO : 2
Sorted Array :
N CPU
8 10.9
6 5.1
PROGRAM 5: write a program to find the value of an (where a and n are integers) using both brute-force
based algorithm and Divide and Conquer based algorithm
pow = 1
for i in range(n):
pow = pow * a
return pow
if y == 0:
return 1
half_power = dpower(x, y // 2)
else: # y is odd
half_power = dpower(x, y // 2)
# Main block
if __name__ == "__main__":
a = int(input("Enter a: "))
n = int(input("Enter n: "))
OUTPUT:
Enter a: 2
Enter n: 10
import timeit
import random
Array.append(ele)
# divide function
i = (low - 1)
# increment
i=i+1
return (i + 1)
quickSort(Array, low, pi - 1)
quickSort(Array, pi + 1, high)
# Main Block
N = []
CPU = []
trail = int(input("Enter number of trials: ")) # corrected typo from "trails" to "trials"
Array = []
Input(Array, n)
start = timeit.default_timer()
quickSort(Array, 0, n - 1)
print("Sorted Array:")
print(Array)
N.append(n)
print("N CPU")
print(N[t], CPU[t])
# Plotting Graph
plt.plot(N, CPU)
plt.show()
OUTPUT:
Sorted Array:
Sorted Array:
Sorted Array:
N CPU
6 21.7
7 7.7
4 7.1
PROGRAM 7: write a program to find the binomial co-efficient C(n, k),[where n and k are integers and n>k]
using Brute force based algorithm and also dynamic programming based algorithm
# The value of C(n, k) can be recursively calculated using the standard formula for Binomial
Coefficients.
# C(n, 0) = C(n, n) = 1
if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
# Base Cases
if j == 0 or j == i:
C[i][j] = 1
else:
return C[n][k]
# Main block
n = int(input("Enter n: "))
k = int(input("Enter k: "))
OUTPUT:
Enter n: 5
Enter k: 3
PROGRAM 8: write a program to implement Floyd’s algorithm and find the lengths of the shortest paths
from every pairs of vertices in a given weighted graph
# Number of vertices
nV = 4
# Algorithm
def floyd(G):
for r in range(nV):
for p in range(nV):
for q in range(nV):
sol(dist)
def sol(dist):
for p in range(nV):
for q in range(nV):
if dist[p][q] == INF:
else:
G=[
[15, INF, 5, 0]
floyd(G)
OUTPUT:
0 5 15 10
20 0 10 5
30 35 0 15
15 20 5 0
PROGRAM 9: write a program to evaluate a polynomial using brute-force based algorithm and using
Horner’s rule and compare their performances
import timeit
"""
"""
result = 0
for i in range(n):
Sum = poly[i]
Sum = Sum * x
print("Value of polynomial 2x3 - 6x2 + 2x - 1 for x = 3 using [BRUTE FORCE method]:", result)
"""
"""
res = poly[0]
# Main block
n = len(poly)
start1 = timeit.default_timer()
polynomial_BF(poly, x, n)
t1 = timeit.default_timer() - start1
start2 = timeit.default_timer()
horner(poly, x, n)
t2 = timeit.default_timer() - start2
OUTPUT:
PROGRAM 10: write a program to solve the string matching problem using Boyer-Moore approach.
m = len(pattern)
n = len(text)
if m > n:
return -1
skip = []
for k in range(256):
skip.append(m)
for k in range(m - 1):
skip[ord(pattern[k])] = m - k - 1
skip = tuple(skip)
while k < n:
j -= 1
i -= 1
return i + 1
# Main block
if __name__ == '__main__':
pattern = "the"
s = BoyerMooreHorspool(pattern, text)
print('Text:', text)
print('Pattern:', pattern)
if s > -1:
print('Pattern "' + pattern + '" found at position', s)
else:
OUTPUT:
Pattern: the
PROGRAM 11: write a program to solve the string matching problem using KMP algorithm
# Preprocess the pattern to create the longest prefix suffix (LPS) array
m = len(pattern)
n = len(text)
lps = [0] * m
computeLPSArray(pattern, m, lps)
while i < n:
if pattern[j] == text[i]:
i += 1
j += 1
if j == m: # A match is found
if j != 0:
j = lps[j - 1]
else:
i += 1
return initial_index
i=1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
# Main module
if __name__ == "__main__":
string = "ABABDABACDABABCABABCABAB"
pat = "ABABCABAB"
print("Pattern:", pat)
if initial_index:
for i in initial_index:
else:
OUTPUT:
string: ABABDABACDABABCABABCABAB
Pattern: ABABCABAB
graph = {
'7': ['8'],
'2': [],
'4': ['8'],
'8': []
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
for neighbour in graph[m]: # Iterate through all neighbours of the dequeued node
queue.append(neighbour) # Enqueue it
# Main module
OUTPUT:
5 3 7 2 4 8
PROGRAM 13: write a program to find the minimum spanning tree of a given graph using prim’s algorithm
INF = 9999999
V=5
G=[
[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]
selected = [False] * V
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
minimum = INF
x=0
y=0
for i in range(V):
for j in range(V):
# Check for edges from i to j that are not yet included in MST
minimum = G[i][j]
x=i
y=j
OUTPUT:
Edge : Weight
0-1:2
1-2:3
1-4:5
0-3:6
PROGRAM 14: write a program to obtain the topological ordering of vertices in a given digraph. Compute
the transitive closure of a given directed graph using Warshall’s algorithm
# Complexity: O(V^3)
class Graph:
self.V = vertices
for i in range(self.V):
for j in range(self.V):
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
self.printSolution(reach)
# Main module
g = Graph(4)
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]]
g.transitiveClosure(graph)
OUTPUT:
1 1 1 1
0 1 1 1
0 0 1 1
0 0 0 1
PROGRAM 15: write a program to find a subset of a given set S={s1,s2,sn} of n positive integers whose....
sum is equal to a given positive integer d. For example, if S={1,2,5,6,8} and d=9 there are two solutions
{1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesn’t have a
solution.
for i in range(n):
S.append(ele)
count = 0
# Check all possible subsets
if sum(my_sub_set) == d:
count += 1
if count == 0:
# Main module
S = []
Input(S, n)
print("Input set:", S)
sub_set_sum(n, S, d)
OUTPUT:
Enter size: 4
Arr: 1
Arr: 2
Arr: 3
Arr: 4
Enter sum d: 5
[1, 4]
[2, 3]
Enter size: 3
Arr: 1
Arr: 2
Arr: 5
Enter sum d: 20