DAA Lab Programs banglore university buc
DAA Lab Programs banglore university buc
1. Write a program to implement linear 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 time taken versus n.
import timeit
def Input(Array,n):
for i in range(0,n):
ele=int(input("Arr:"))
Array.append(ele)
#Linear searching
def linear_search(Array,key):
for x in Array:
if x==key:
return True
return False
#Main Block
N=[]
CPU=[]
for t in range(0,trail):
Array=[]
print("----->TRAIL NO:",t+1)
Input(Array,n)
print(Array)
key=int(input("Enter key:"))
start=timeit.default_timer()
s=linear_search(Array,key)
print("Element Found=",s)
times=timeit.default_timer()-start
N.append(n)
CPU.append(round(float(times)*1000000,2))
print("N CPU")
for t in range(0,trail):
print(N[t],CPU[t])
#plotting Graph
plt.plot(N,CPU)
plt.scatter(N,CPU,color="red",marker="*",s=50)
plt.xlabel('Array Size-n')
plt.show()
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 time taken versus n.
import timeit
def Input(Array,n):
for i in range(0,n):
ele=int(input("Arr:"))
Array.append(ele)
#Binary searching
def binary_search(Array,x,low,high):
if high>=low:
mid=low+(high-low)//2
if Array[mid]==x:
return mid
elif Array[mid]>x:
return binary_search(Array,x,low,mid-1)
else:
return binary_search(Array,x,mid+1,high)
else:
return-1
#Main Block
N=[]
CPU=[]
for t in range(0,trail):
Array=[]
print("----->TRAIL NO:",t+1)
Input(Array,n)
print(Array)
x=int(input("Enter key:"))
start=timeit.default_timer()
s=binary_search(Array,x,0,len(Array)-1)
print("Element Found=",s+1)
times=timeit.default_timer()-start
N.append(n)
CPU.append(round(float(times)*1000000,2))
print("N CPU")
for t in range(0,trail):
print(N[t],CPU[t])
#plotting Graph
plt.plot(N,CPU)
plt.scatter(N,CPU,color="red",marker="*",s=50)
plt.xlabel('Array Size-N')
plt.show()
3. Write a program to solve towers of Hanoi problem and execute it for different number of disks
def TowerOfHonai(n, source, destination, auxillary):
if n==1:
#main block
4. Write a program to sort a given set of numbers using selection sort algorithm. Repeat the experiment
for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken
versus n.
import timeit
import random
def Input(Array,n):
for i in range(0,n):
ele=random.randrange(1,50)
Array.append(ele)
#Selection Sort
def selectionSort(Array,size):
for i in range(size):
Min=i
for j in range(i+1,size):
if Array[j]<Array[Min]:
Min=j
(Array[i],Array[Min])=(Array[Min],Array[i])
#Main Block
N=[]
CPU=[]
for t in range(0,trial):
Array=[]
print("--->TRIAL NO:",t+1)
Input(Array,n)
print(Array)
start=timeit.default_timer()
selectionSort(Array,n)
times=timeit.default_timer()-start
print("Sorted Array:")
print(Array)
N.append(n)
CPU.append(round(float(times)*100000,2))
print("N CPU")
for t in range(0,trial):
print(N[t],CPU[t])
#Plotting Graph
plt.plot(N,CPU)
plt.scatter(N,CPU,color="red",marker="*",s=50)
plt.xlabel("Array Size(N)")
plt.show()
5. Write a program to find an using (a) Brute-force based algorithm (b) Divide and conquer based
algorithm
def bpower(a, n):
pow=1
for i in range(n):
pow=pow*a
return pow
if(y==0):
return 1
elif(int(y%2)==0):
else:
#main block
a=int(input("Enter a:"))
n=int(input("Enter n:"))
6. Write a program to sort a given set of numbers using quick sort algorithm. Repeat the experiment for
different values of n, the number of elements in the list to be sorted and plot a graph of the time taken
versus n.
import timeit
import random
Array.append(ele)
# Partition function
i = low - 1
pivot = Array[high]
for j in range(low, high):
i += 1
return i + 1
quickSort(Array, low, pi - 1)
quickSort(Array, pi + 1, high)
# Main Block
N = []
CPU = []
Array = []
Input(Array, n)
start = timeit.default_timer()
quickSort(Array, 0, n - 1)
print("Sorted Array:")
print(Array)
N.append(n)
# Display results
print("N\tCPU")
print(f"{N[t]}\t{CPU[t]}")
# Plotting Graph
plt.plot(N, CPU)
plt.show()
7. Write a program to find binomial co-efficient C (n, k) [ where n and k are integers and n > k] using
brute force algorithm and also dynamic programming-based algorithm.
def binomialCoeff_BF(n, k):
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: "))
8. Write a program to implement Floyd’s algorithm and find the lengths of the shortest paths from every
pair of vertices in a weighted graph.
# Number of vertices
nV = 4
INF = 999
# 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:
print(" ")
# Input
floyd(G)
9. Write a program to evaluate polynomial using brute-force 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 2x^3 - 6x^2 + 2x - 1 for x = 3 using [BRUTE FORCE method]:", result)
# Horner's Method
res = poly[0]
# Main Block
x=3
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
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
visited.append(node)
queue.append(node)
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
11. Write a program to obtain the transitive closure of a given directed graph using Warshall’s algorithm.
# Class to represent a graph
class Graph:
self.V = vertices
for i in range(self.V):
for j in range(self.V):
if i == j:
else:
print()
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)
graph = [
[1, 1, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]
g.transitiveClosure(graph)
12. . Write a program to find subset of a given set S= {s1, s2,.sn} of n positive integers whose sum is equal
to given positive integer d.
from itertools import combinations
ele=int(input("Arr : "))
S.append(ele)
count=0
for i in range(size+1):
if sum(my_sub_set) == d:
print(list(my_sub_set))
count=count+1
if(count==0):
print("Subset Not found for the given d=",d)
#main block
S=[]
n=int(input("Enter Size:"))
Input(S, n)
print(S)
sub_set_sum(n, S, d)