Algorithms Lab
Algorithms Lab
Linear Search
DATE:
Aim
Algorithm
Program
import time
import numpy as np
start = time.time()
def search(ls, x):
for i in range(len(ls)):
if ls[i] == x:
return i
n = int(input("Enter number of elements : "))
a = list(map(int,input("\nEnter the elements : ").strip().split()))[:n]
key = int(input("Enter the element to search : "))
print("Your element is present at index ",search(a,key))
end = time.time()
ti = end-start
print("Time taken to search :",ti)
Output
Enter number of elements : 5
Enter the elements : 3 4 5 6 1
Enter the element to search : 5
Your element is present at index 2
Time taken to search : 10.700574398040771
Result
EX NO :
Aim
Algorithm
Program
import time
start = time.time()
def BinarySearch(arr, k, low, high):
if high >= low:
mid = low + (high - low)//2
if arr[mid] == k:
return mid
elif arr[mid] > k:
return BinarySearch(arr, k, low, mid-1)
else:
return BinarySearch(arr, k, mid + 1, high)
else:
return -1
arr = [1, 3, 5, 7, 9]
print(arr)
k = int(input(“enter the element at array:”))
result = BinarySearch(arr, k, 0, len(arr)-1)
if result != -1:
print("Element is present at index " +
str(result)) else:
print("Not found")
BinarySearch(arr, k, 0, len(arr)-1)
end = time.time()
print("Time taken to search: ",start-end ,"seconds")
Output
[1, 3, 5, 7, 9]
Enter an element from array: 5
Element is present at index 2
Time taken to search: -4.114552736282349 seconds
Result
EX NO :
Aim
Algorithm
Program
def search(pat, txt):
M = len(pat)
N = len(txt)
for i in range(N - M + 1):
j=0
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
txt = input('Enter the text : ')
pat = input("Enter the pattern : ")
search(pat,txt)
Output
Enter the text : banana
Enter the pattern : na
Pattern found at index 2
Pattern found at index 4
Result:
EX NO :
DATE: Insertion Sort
Aim:
Algorithm:
Program
import time
start =time.time()
def InsertionSort(a):
for i in range(1, len(a)):
temp = a[i]
j = i-1
while j >=0 and temp < a[j] :
a[j+1] = a[j]
j -= 1
a[j+1] = temp
a = [10, 5, 13, 8, 2]
print("Before after sorting:")
print(a)
InsertionSort(a)
print("Array after sorting:")
print(a)
end =time.time()
print("Time taken for searching",end-start,"seconds")
Output
Before after sorting:
[10, 5, 13, 8, 2]
Array after sorting:
[2, 5, 8, 10, 13]
Time taken for searching 0.1542215347290039 seconds
Result:
EX NO :
Aim
Algorithm
Program
import time
start = time.time()
def heapify(array, a, b):
largest = b
l=2*b+1
root = 2 * b + 2
if l < a and array[b] < array[l]:
largest = l
if root < a and array[largest] < array[root]:
largest = root
# Change root
if largest != b:
array[b], array[largest] = array[largest], array[b]
heapify(array, a, largest)
# sort an array of given size
def Heap_Sort(array):
a = len(array)
# maxheap..
for b in range(a // 2 - 1, -1, -1):
heapify(array, a, b)
# extract elements
print(start)
Heap_Sort(array)
#end= time.time()
a = len(array)
print ("Array after sorting is: \n", array)
end= time.time()
def measure_heap_sort_time(array):
start_time = time.time()
Heap_sort(array)
end_time = time.time()
return end_time - start_time
Output
The original array is:
[7, 2, 5, 6, 3, 1, 8, 4]
Array after sorting is:
[1, 2, 3, 4, 5, 6, 7, 8]
The required time is: 0.14311861991882
Result
EX NO :
DATE:
Breadth First Search
Aim
Algorithm
Program
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 = {start}
queue = deque([start])
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbour in self.adjacency_list[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 5)
012345
Result
EX NO :
Depth First Search
DATE:
Aim
Algorithm
Program
class Graph:
def _init_(self):
self.adjacency_list = {}
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)
visited.add(vertex)
self.dfs_util(neighbour, visited)
visited = set()
self.dfs_util(start, visited)
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 5)
g.add_edge(4, 5)
print(“The DFS of the graph is:”)
g.dfs(2)
Output
The DFS of the graph is:
013452
Result
EX NO :
Pattern Searching
DATE:
Aim
Algorithm
Program
import heapq
distances[start] = 0
while heap:
continue
distances[neighbor] = distance
return distances
'E': {}
start_vertex = 'A'
Result
EX NO :
Aim
Algorithm
Program
import heapq
def prim(graph):
visited = set()
minimum_spanning_tree = []
start_vertex = list(graph.keys())[0]
visited.add(start_vertex)
heapq.heapify(edges)
while edges:
continue
return minimum_spanning_tree
min_spanning_tree=prim(graph)
Output:
The minimum spanning tree using prim's algorithm is:
[('A', 'B', 2), ('D', 'D', 3), ('C', 'C', 1), ('E', 'E', 1)]
Result
EX NO :
Floyd’s algorithm
DATE:
Aim
Algorithm
AA
Program
def floyd(graph):
for i in range(len(graph)):
for j in range(len(graph)):
if graph[i][j] != 0:
distance_matrix[i][j] = graph[i][j]
for k in range(len(graph)):
for i in range(len(graph)):
for j in range(len(graph)):
I = float('inf')
[4, 0, 3, I],
[I, I, 0, 2],
[I, -1, I, 0]
floyd(adjMatrix)
Output
The shortest distance matrix is:
[[0, -1, -2, 0], [4, 0, 2, 4], [5, 1, 0, 2], [3, -1, 1, 0]]
Result
EX NO :
Aim
Algorithm
Program
from collections import defaultdict
class Graph:
self.V = vertices
for i in range(self.V):
for j in range(self.V):
if (i == j):
else:
print()
def transitiveClosure(self,graph):
reach =[i[:] for i in graph]
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
self.printSolution(reach)
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
Result
EX NO :
Maximum and Minimum numbers in a given list
DATE:
Aim
Algorithm
Program
def getMinMax(low, high, arr):
arr_max = arr[low]
arr_min = arr[low]
if low == high:
arr_max = arr[low]
arr_min = arr[low]
arr_max = arr[low]
arr_min = arr[high]
else:
arr_max = arr[high]
arr_min = arr[low]
else:
high = len(arr) - 1
low = 0
arr_max, arr_min = getMinMax(low, high, arr)
print('Minimum element is ', arr_min)
print('Maximum element is ', arr_max)
Output
Minimum element is 1
Result
EX NO :
Merge Sort
DATE:
Aim
Algorithm
Program
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
left = merge_sort(left)
right = merge_sort(right)
result = []
i=0
j=0
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
a=[20,12,34,10,52,19]
Output
The sorted array using merge sort: 10,12,19,20,34,52
Result
.
EX NO :
Quick sort
DATE:
Aim
Algorithm
Program
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
less = []
greater = []
equal = []
less.append(element)
greater.append(element)
else:
equal.append(element)
sorted_less = quick_sort(less)
sorted_greater = quick_sort(greater)
a=[20,12,34,10,52,19]
Result
EX NO :
Implement N Queens problem using Backtracking
DATE:
Aim
Algorithm
Program
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print()
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solveNQ():
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
if solveNQUtil(board, 0) == False:
return False
printSolution(board)
return True # Driver Code solveNQ()
Output
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Result
EX NO :
Finding the kth smallest number using randomized algorithm
DATE:
Aim
Algorithm
.
Program
import random
pos = randomPartition(arr, l, r)
if (pos - l == k - 1):
return arr[pos]
return 999999999999
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
x = arr[r]
i=l
swap(arr, i, j)
i += 1
swap(arr, i, r)
return i
def randomPartition(arr, l, r):
n=r-l+1
pivot = int(random.random() * n)
swap(arr, l + pivot, r)
return partition(arr, l, r)
# Driver Code
n = len(arr)
k=3
Output
K'th smallest element is 5
Result