Algorithms Lab Manual
Algorithms Lab Manual
6. 19
Develop a program to implement graph traversal using
Depth First Search
3
9. Implement Floyd’s algorithm for the All-Pairs- 26
Shortest-Paths problem
4
Ex.No:1 Implement Linear Search, Determine the time required to search for an
element. Repeat the experiment for different values of n, the number of
Date: elements in the list to be searched and plot a graph of the time taken
versus n
AIM:
To write a python program to implement Linear Search. Determine the time required to search for
an element. 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.
ALGORITHM:
Step 1: First, read the search element (Target element) in the array.
Step 2: Set an integer i = 0 and repeat steps 3 to 4 till i reaches the end of the array.
PROGRAM:
import time
import random
def linear_search(arr,x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
n_values = [10,100,500,550,600,700]
times = []
for n in n_values:
x = random.randint(0,n)
5
start_time = time.time()
result = linear_search(arr,x)
end_time = time.time()
times.append(end_time - start_time)
if result != -1:
else:
print(f"Timetaken:{end_time - start_time}\n")
plt.plot(n_values,times)
plt.xlabel("n")
plt.ylabel("Time taken")
plt.show()
OUTPUT:
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
6
RESULT:
Thus the python program to implement Linear Search. Determine the time required to search for
an element. 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 was executed and the output is verified successfully.
7
Ex.No:2 Implement recursive Binary Search. Determine the time required to
search an element. Repeat the experiment for different values of n, the
Date: number of elements in the list to be searched and plot a graph of the
time taken versus n.
AIM:
To write a python program to implement recursive Binary Search. Determine the time required to
search an element. 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.
ALGORITHM:
Step 4: Divide the list using probing formula and find the new midle.
PROGRAM:
import time
import random
def binary_search(arr,left,right,x):
if arr[mid] == x:
return mid
return binary_search(arr,left,mid-1,x)
8
else:
return binary_search(arr,mid+1,right,x)
else:
return -1
n_values = [10,100,500,550,600,700]
times = []
for n in n_values:
x = random.choice(arr)
start_time = time.time()
result = binary_search(arr,0,len(arr)-1,x)
end_time = time.time()
times.append(end_time - start_time)
if result != -1:
else:
print(f"Timetaken:{end_time - start_time}\n")
plt.plot(n_values,times)
plt.xlabel("n")
plt.ylabel("Time taken")
plt.show()
9
OUTPUT:
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
Timetaken:0.0
RESULT:
Thus the python program for to implement recursive Binary Search. Determine the time required
to search an element. 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 was executed and the output is verified
successfully.
10
Ex.No:3 Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function
search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in
Date: txt [ ]. You may assume that n > m.
AIM:
To write a python program to Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function
search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.
ALGORITHM:
Step 2: Initialize an empty list to store the positions where the pattern is found.
a. Check if the substring T[i:i+len(P)] equals P, where len(P) is the length of the
pattern.
b. If the substring matches the pattern, append the position i to the list of the matches.
PROGRAM:
M = len(pat)
N = len(txt)
j=0
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
if __name__ == '__main__':
11
txt = "AABAACAADAABAAABAA"
pat = "AABA"
search(pat, txt)
OUTPUT:
RESULT:
Thus the python program for to given a text txt [0...n-1] and a pattern pat [0...m-1], write a
function search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume
that n > m was executed and the output is verified successfully.
12
Ex.No:4 Sort a given set of elements using the Insertion sort and Heap sort
methods and determine the time required to sort the elements. Repeat
Date: 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.
AIM:
To write a python program to sort a given set of elements using the Insertion sort and Heap sort
methods and determine the time required to sort the elements. 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.
ALGORITHM:
Insertion Sort:
Step 1: The procedure takes a single argument, ‘A’, which is a list of sortable items.
Step 3: The outer for loop starts at index ‘1’ and runs for ‘n-1’ iterations, where ‘n’ is the length of
the array.
Step 4: The inner while loop starts at the current index i of the outer for loop and compares each
element to its left neighbor. If an element is smaller than its left neighbor, the elements are swapped.
Step 5: The inner while loop continues to move an element to the left as long as it is smaller than the
element to its left.
Step 6: Once the inner while loop is finished, the element at the current index is in its correct position
in the sorted portion of the array.
Step 7: The outer for loop continues iterating through the array until all elements are in their correct
positions and the array is fully sorted.
Heap sort:
Step 1: First convert the array into heap data structure using heapify, then one by one delete the
root node of the Max-heap and replace it with the last node in the heap and then heapify the root
of the heap. Repeat this process until size of heap is greater than 1.
Step 3: Repeat the following steps until the heap contains only one element:
a. Swap the root element of the heap (which is the largest element) with the last element
of the heap.
13
b. Remove the last element of the heap (which is now in the correct position).
c. Heapify the remaining elements of the heap.
PROGRAM:
import random
import time
def insertion_sort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
def heap_sort(arr):
def heapify(arr,n,i):
largest = i
l = 2*i+1
r = 2*i+1
largest = l
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr,n,largest)
n = len(arr)
14
heapify(arr,n,i)
for i in range(n-1,0,-1):
arr[0],arr[i] = arr[i],arr[0]
heapify(arr,i,0)
n_values = [10,100,1000,100000]
insertion_sort_times = []
heap_sort_times = []
for n in n_values:
start_time = time.time()
insertion_sort(arr)
end_time = time.time()
insertion_sort_times.append(end_time - start_time)
start_time = time.time()
heap_sort(arr)
end_time = time.time()
heap_sort_times.append(end_time - start_time)
plt.plot(n_values,insertion_sort_times,label="Insertion Sort")
plt.plot(n_values,heap_sort_times,label="Heap Sort")
plt.xlabel("Number of elements")
plt.legend()
plt.show()
15
OUTPUT:
RESULT:
Thus the python program to sort a given set of elements using the Insertion sort and Heap
sort methods and determine the time required to sort the elements. 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 was
executed and the output is verified successfully.
16
Ex.No:5
AIM:
To write a python program to develop a program to implement graph traversal using Breadth First
Search.
ALGORITHM:
Step 1: Create a recursive function that takes the index of the node and a visited array.
Step 2: Mark the current node as visited and print the node.
Step 3: Traverse all the adjacent and unmarked nodes and call the recursive function with the index
of the adjacent node.
PROGRAM:
'B': ['A','D','E'],
'C': ['A','F'],
'D': ['B'],
'E': ['B','F'],
'F': ['C','E']}
def bfs(graph,start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node,end='')
17
for neighbor in graph[node]:
visited.add(neighbor)
queue.append(neighbor)
bfs(graph,'A')
OUTPUT:
ABCDEF
RESULT:
Thus the python program to develop a program to implement graph traversal using Breadth First
Search.
18
Ex.No:6
AIM:
To write a python program to Develop a program to implement graph traversal using Depth First
Search.
ALGORITHM:
Step 2: Select any vertex in your graph (say v1), from which you want to traverse the graph.
Step 3: Utilize the following two data structures for traversing the graph.
Step 4: Add the starting vertex to the visited array, and afterward, you add v1’s adjacent vertices
to the queue data structure.
Step 5: Now using the FIFO concept, remove the first element from the queue, put it into the
visited array, and then add the adjacent vertices of the removed element to the queue.
Step 6: Repeat step 5 until the queue is not empty and no vertex is left to be visited.
PROGRAM:
def dfs(graph,start):
visited = set()
stack = [start]
while stack:
node = stack.pop()
visited.add(node)
stack.extend(graph[node] - visited)
return visited
19
graph = { 'A': {'B','C'},
'B': {'A','D','E'},
'C': {'A','F'},
'D': {'B'},
'E': {'B','F'},
'F': {'C','E'}}
print(dfs(graph,'A'))
OUTPUT:
RESULT:
Thus the python program for to Develop a program to implement graph traversal using Depth
First Search was executed and the output is verified successfully.
20
Ex.No:7
AIM:
To write python program from a given vertex in a weighted connected graph, develop a program
to find the shortest paths to other vertices using Dijkstra’s algorithm.
ALGORITHM:
Step 1: Start from Node 0 and mark Node as visited as you can check in below image visited
Node is marked red.
Step 2: Check for adjacent Nodes, Now we have to choices (Either choose Node1 with distance 2
or either choose Node 2 with distance 6 ) and choose Node with minimum distance. In this
step Node 1 is Minimum distance adjacent Node, so marked it as visited and add up the distance.
Step 3: Then Move Forward and check for adjacent Node which is Node 3, so marked it as
visited and add up the distance
Step 4: Again we have two choices for adjacent Nodes (Either we can choose Node 4 with
distance 10 or either we can choose Node 5 with distance 15) so choose Node with minimum
distance. In this step Node 4 is Minimum distance adjacent Node, so marked it as visited and add
up the distance.
Step 5: Again, Move Forward and check for adjacent Node which is Node 6, so marked it as
visited and add up the distance
PROGRAM:
import heapq
distances[start] = 0
pq = [(0, start)]
while pq:
21
new_dist = dist + weight
distances[adj_node] = new_dist
heapq.heappush(pq,(new_dist, adj_node))
return distances
graph = {
'A':{'B':3,'D':2},
'B':{'A':3,'C':4,'D':5},
'C':{'B':4,'D':1},
'D':{'A':2,'B':5,'C':1}
start_node = 'A'
print(dijkstra(graph, start_node))
OUTPUT:
RESULT:
Thus the python program for to from a given vertex in a weighted connected graph, develop a
program to find the shortest paths to other vertices using Dijkstra’s algorithm was executed and the output
is verified successfully.
22
Ex.No:8
Date: Find the minimum cost spanning tree of a given undirected graph using
Prim’s algorithm
AIM:
To write a python program to find the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm.
ALGORITHM:
PROGRAM:
import sys
class Graph():
self.V = vertices
print("Edge \tWeight")
print(parent[i], '-',i,'\t',self.graph[i][parent[i]])
23
min = sys.maxsize
for v in range(self.V):
min = key[v]
min_index = v
return min_index
def primMST(self):
key[0] = 0
parent[0] = -1
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
if __name__ == '__main__':
g = Graph(5)
24
g.graph = [[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]]
g.primMST()
OUTPUT:
Edge Weight
0-1 2
1-2 3
4-3 9
2-4 7
RESULT:
Thus the python program to find the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm was executed and the output is verified successfully.
25
Ex.No:9
AIM:
To write a python program to implement Floyd’s algorithm for the All-Pairs- Shortest-Paths
problem.
ALGORITHM:
Step 4: If both pointers meet at some point then a loop exists and if the fast pointer meets the end
position then no loop exists.
PROGRAM:
V=4
INF = 99999
def floydWarshall(graph):
for k in range(V):
for i in range(V):
for j in range(V):
printSolution(dist)
def printSolution(dist):
print("Following matrix shows The shortest distance between every pair of vertices")
for i in range(V):
for j in range(V):
if(dist[i][j] == INF):
26
print("%7s\t" % ("INF"), end=' ')
else:
if j == V-1:
print()
if __name__ == '__main__':
graph = [[0,5,INF,10],
[INF,0,3,INF],
[INF,INF,0,1],
[INF,INF,INF,0]]
floydWarshall(graph)
OUTPUT:
Following matrix shows The shortest distance between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
RESULT:
Thus the python program to implement Floyd’s algorithm for the All-Pairs- Shortest-Paths
problem.
27
Ex.No:10
AIM:
To write a python program to compute the transitive closure of a given directed graph using
Warshall's algorithm.
ALGORITHM:
Step 4: If both pointers meet at some point then a loop exists and if the fast pointer meets the end
position then no loop exists.
PROGRAM:
class Graph():
self.V = vertices
for i in range(self.V):
for j in range(self.V):
if (i == j):
else:
print()
28
def transitiveClosure(self, 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)
graph = [[1,1,0,1],
[0,1,1,0],
[0,0,1,1],
[0,0,0,1]]
g.transitiveClosure(graph)
OUTPUT:
1 1 0 1
0 1 1 0
0 0 1 1
0 0 0 1
RESULT:
Thus the python program to compute the transitive closure of a given directed graph using
Warshall's algorithm was executed and the output is verified successfully.
29
Ex.No:11
Date: Develop a program to find out the maximum and minimum numbers in
a given list of n numbers using the divide and conquer technique
AIM:
To write a python program to develop a program to find out the maximum and minimum numbers
in a given list of n numbers using the divide and conquer technique
ALGORITHM:
To find Maximum
Step 1: Initialize a variable max_num with the first number in the list.
Step 2: Loop through the list and compare each number with the previous number.
Step 3: If the current number is greater than the maximum number we created above, then update
the max_num variable with the current number.
Step 4: If the current number is less than the previous number, then do nothing.
To find Minimum
Step 1: Initialize a variable min_num with the first number in the list.
Step 2: Use for loop to loop through the list and check if the current number is less than our
minimum number.
Step 3: If the current number is less than the minimum number, then update
the min_num variable with the current number.
PROGRAM:
maximum = -1
return arr[ind]
else:
return arr[ind + 1]
30
maximum = divideandConquer_Max(arr, ind + 1, len)
return arr[ind]
else:
return maximum
minimum = 0
return arr[ind]
else:
return arr[ind + 1]
return arr[ind]
else:
return minimum
if __name__ == '__main__':
minimum, maximum = 0, -1
arr = [6,4,8,90,12,56,7,1,63]
maximum = divideandConquer_Max(arr,0,9)
minimum = divideandConquer_Min(arr,0,9)
31
OUTPUT:
RESULT:
Thus the python program to develop a program to find out the maximum and minimum numbers
in a given list of n numbers using the divide and conquer technique was executed and the output is
verified successfully.
32
Ex.No:12 Implement Merge sort and Quick sort methods to sort an array of
elements and determine the time required to sort. Repeat the
Date: 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.
AIM:
To write a python program to implement Merge sort and Quick sort methods to sort an array of
elements and determine the time required to sort. 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.
ALGORITHM:
Merge Sort
import random
import time
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
33
right = merge_sort(arr[mid:])
return merge(left,right)
result = []
i=j=0
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
n_values = [10,100,1000,10000,100000]
merge_sort_times = []
quick_sort_times = []
for n in n_values:
34
arr = [random.randint(1,1000)for _ in range(n)]
start_time = time.time()
sorted_arr = merge_sort(arr)
merge_sort_times.append(merge_sort_time)
start_time = time.time()
sorted_arr = quick_sort(arr)
quick_sort_times.append(quick_sort_time)
plt.plot(n_values,merge_sort_times,label="Merge Sort")
plt.plot(n_values,quick_sort_times,label="Quick Sort")
plt.xlabel("n")
plt.ylabel("Time(s)")
plt.legend()
plt.show()
OUTPUT:
35
RESULT:
Thus the python program to implement Merge sort and Quick sort methods to sort an array of
elements and determine the time required to sort. 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 was executed and
the output is verified successfully.
36
Ex.No:13
AIM:
ALGORITHM:
Step 2: Start with the leftmost column and place a queen in the first row of that column.
Step 3: Move to the next column and place a queen in the first row of that column.
Step 4: Repeat step 3 until either all N queens have been placed or it is impossible to place a
queen in the current column without violating the rules of the problem.
Step 6: If it is not possible to place a queen in the current column without violating the rules of
the problem, backtrack to the previous column.
Step 7: Remove the queen from the previous column and move it down one row.
Step 8: Repeat steps 4-7 until all possible configurations have been tried.
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:
37
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
def solveNQUtil(board,col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
return True
board[i][col] = 0
return False
def solveNQ():
board = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
if solveNQUtil(board, 0) == False:
return False
38
printSolution(board)
return True
solveNQ()
OUTPUT:
0010
1000
0001
0100
RESULT:
Thus the python program to Implement N Queens problem using Backtracking was executed
and the output is verified successfully.
39