0% found this document useful (0 votes)
17 views44 pages

Algorithm Record

Algorithm record

Uploaded by

shivani20.dsp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views44 pages

Algorithm Record

Algorithm record

Uploaded by

shivani20.dsp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Ex.

No: 1
IMPLEMENT LINEAR SEARCH
Date:

AIM:

To implement Linear search and determine the time required to search an element and plot a graph of
time Taken versus n.

ALGORITHM:
Step 1: Start.

Step 2: Define linear search function.

Step 3: Define run-experiment to find the time taken.

Step 4: Create an array with number of elements in the list to find the time taken.

Step 5: Plot the time taken vs n using pyplot.

Step 6: Stop.

PROGRAM:

import time
import matplotlib.pyplot as plt

def linear_search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1

# perform linear search on multiple arrays


ns = []
times = []
while True:
# get the value of n from the user
n = int(input("Enter the number of elements: "))

1
# get the elements of the array from the user
arr = []
for i in range(n):
x = int(input(f"Enter element {i}: "))
arr.append(x)

# get the value to search for from the user


x = int(input("Enter the element to search for: "))

# time the search


start_time = time.perf_counter()
index = linear_search(arr, x)
end_time = time.perf_counter()

if index != -1:
print(f"Found element {x} at index {index}")
else:
print(f"Element {x} not found")

# print the time taken


time_taken = end_time - start_time
print(f"Time taken to search for {x} in array of size {n}: {time_taken} seconds\n")

# add the time and n values to the lists


ns.append(n)
times.append(time_taken)

# ask if the user wants to search another array


choice = input("Do you want to search another array? (y/n) ")

2
if choice.lower() != 'y':
break
# plot a graph of the time taken versus n
plt.plot(ns, times)
plt.xlabel("Time taken (seconds)")
plt.ylabel("n")
plt.show()
OUTPUT:
Enter the number of elements: 5
Enter element 0: 54
Enter element 1: 76
Enter element 2: 83
Enter element 3: 26
Enter element 4: 54
Enter the element to search for: 76
Found element 76 at index 1
Time taken to search for 76 in array of size 5: 2.1199986804276705e-05 seconds

Do you want to search another array? (y/n) y


Enter the number of elements: 5
Enter element 0: 65
Enter element 1: 23
Enter element 2: 49
Enter element 3: 86
Enter element 4: 54
Enter the element to search for: 54
Found element 54 at index 4
Time taken to search for 54 in array of size 5: 2.4699955247342587e-05 seconds

Do you want to search another array? (y/n) y


Enter the number of elements: 6
Enter element 0: 73

3
Enter element 1: 28
Enter element 2: 52
Enter element 3: 39
Enter element 4: 65
Enter element 5: 99
Enter the element to search for: 99
Found element 99 at index 5
Time taken to search for 99 in array of size 6: 2.400000812485814e-05 seconds
Do you want to search another array? (y/n) n

RESULT:

Thus the implementation of linear search has been executed successfully.

4
Ex.No: 2
IMPLEMENT BINARY SEARCH
Date:

AIM:

To implement recursive binary search and determine the time required to search an element and plot a
graph of time Taken versus n.

ALGORITHM:

Step1: Start.

Step 2: Define recursive binary search.

Step 3: Import time module to determine the time taken to search an element.

Step 4: Plot the time taken vs n using pyplot.

Step 5: Stop.

PROGRAM:
import time
import matplotlib.pyplot as plt

def binary_search(arr, x, low, high):


if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
return binary_search(arr, x, mid+1, high)
else:
return binary_search(arr, x, low, mid-1)

# perform binary search on multiple arrays


ns = []
times = []
while True:
# get the value of n from the user

5
n = int(input("Enter the number of elements: "))

# get the elements of the array from the user


arr = []
for i in range(n):
x = int(input(f"Enter element {i}: "))
arr.append(x)

# sort the array


arr.sort()
print(f"Sorted list: {arr}")

# get the value to search for from the user


x = int(input("Enter the element to search for: "))

# time the search


start_time = time.perf_counter()
index = binary_search(arr, x, 0, n-1)
end_time = time.perf_counter()

if index != -1:
print(f"Found element {x} at index {index}")
else:
print(f"Element {x} not found")

# print the time taken


time_taken = end_time - start_time
print(f"Time taken to search for {x} in array of size {n}: {time_taken} seconds\n")

# add the time and n values to the lists


ns.append(n)
times.append(time_taken)

6
# ask if the user wants to search another array
choice = input("Do you want to search another array? (y/n) ")
if choice.lower() != 'y':
break

# plot a graph of the time taken versus n


plt.plot(ns, times)
plt.xlabel("Time taken (seconds)")
plt.ylabel("n")
plt.show()

OUTPUT:
Enter the number of elements: 5
Enter element 0: 45
Enter element 1: 67
Enter element 2: 34
Enter element 3: 13
Enter element 4: 16
Sorted list: [13, 16, 34, 45, 67]
Enter the element to search for: 45
Found element 45 at index 3
Time taken to search for 45 in array of size 5: 1.5400000847876072e-05 seconds

Do you want to search another array? (y/n) y


Enter the number of elements: 4
Enter element 0: 76
Enter element 1: 45
Enter element 2: 38
Enter element 3: 92
Sorted list: [38, 45, 76, 92]
Enter the element to search for: 92
Found element 92 at index 3
Time taken to search for 92 in array of size 4: 2.0899984519928694e-05 seconds

7
Do you want to search another array? (y/n) y
Enter the number of elements: 5
Enter element 0: 34
Enter element 1: 27
Enter element 2: 16
Enter element 3: 27
Enter element 4: 39
Sorted list: [16, 27, 27, 34, 39]
Enter the element to search for: 27
Found element 27 at index 2
Time taken to search for 27 in array of size 5: 1.379998866468668e-05 seconds

Do you want to search another array? (y/n) n

RESULT:

Thus the implementation of binary search has been executed successfully.

8
Ex.No: 3 Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat
Date: [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.

AIM:

To write a program for a text txt[0…n-1] and a pattern pat[0…m-1], using a function search(char pat[],
char txt[]) that prints all occurences of pat[] in txt[].

ALGORITHM:

Step 1: Start.

Step 2: Get the text string and pattern string.

Step 3: Perform search operations.

Step 4: Print the pattern found.

Step 5: Stop.

PROGRAM:
def search(pat, txt):
m = len(pat)
n = len(txt)

# slide pat[] over 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: # pat[0...m-1] matched txt[i...i+m-1]


print("Pattern found at index ", i)

# User interface
def main():
txt = input("Enter the text: ")
pat = input("Enter the pattern to search: ")

9
search(pat, txt)

# Call the main function to run the program


if __name__ == '__main__':
main()
OUTPUT 1:
Enter the text: THIS IS PYTHON PROGRAMMING
Enter the pattern to search: PYTHON
Pattern found at index 8

OUTPUT 2:

Enter the text: AABAACAADAABAABA


Enter the pattern to search: AABA
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12

RESULT:

The program to implement txt and pat using a function search(char pat[],char txt[]) is executed
successfully.

10
Ex.No: 4
INSERTION SORT & HEAP SORT
Date:

AIM:
To write a program to sort a given set of elements using insertion sort and heap sort and to determine
time requited for sorting pot a graph of time taken vs n.
ALGORITHM:

Step 1: Start.
Step 2: Create the array for sorting.
Step 3: Perform insertion sort and heap sort.
Step 4: Display the time requited for sorting.
Step 5: Plot the graph for time taken vs n.
Step 6: End.
PROGRAM:
import random
import time
import matplotlib.pyplot as plt
# Insertion sort
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Heap sort
def heap_sort(arr):
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[l] > arr[largest]:
largest = l

11
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
# Initialize lists to store values of n and time taken for each algorithm
n_values = []
insertion_sort_times = []
heap_sort_times = []
# Prompt the user for permission to perform multiple sorting operations
while True:
choice = input("Do you want to sort a list? (y/n): ")
if choice.lower() != 'y':
break
# Get input from the user
n = int(input("Enter the number of values in the list: "))
lst = []
for i in range(n):
val = int(input("Enter a value for the list: "))
lst.append(val)

# Measure time for Insertion sort and Heap sort


start_time = time.perf_counter()
insertion_sort(lst)
end_time = time.perf_counter()
insertion_sort_time = end_time - start_time
insertion_sort_times.append(insertion_sort_time)
start_time = time.perf_counter()
heap_sort(lst)

12
end_time = time.perf_counter()
heap_sort_time = end_time - start_time
heap_sort_times.append(heap_sort_time)

# Store the value of n


n_values.append(n)
# Print the sorted list and the time taken by each algorithm
print("Sorted list using Insertion sort:", lst)
print("Time taken by Insertion sort: {:.6f} seconds".format(insertion_sort_time))
print("Sorted list using Heap sort:", lst)
print("Time taken by Heap sort: {:.6f} seconds".format(heap_sort_time)

# Plot the graph of time taken versus n for each algorithm


plt.plot(n_values, insertion_sort_times, label='Insertion sort')
plt.plot(n_values, heap_sort_times, label='Heap sort')
plt.xlabel('n')
plt.ylabel('Time taken (seconds)')
plt.title('Sorting algorithms')
plt.legend()
plt.show()

OUTPUT:
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 10
Enter a value for the list: 59
Enter a value for the list: 43
Enter a value for the list: 72
Enter a value for the list: 39
Enter a value for the list: 98
Enter a value for the list: 13
Enter a value for the list: 16
Enter a value for the list: 72
Enter a value for the list: 89
Enter a value for the list: 34
Sorted list using Insertion sort: [13, 16, 34, 39, 43, 59, 72, 72, 89, 98]
Time taken by Insertion sort: 0.000023 seconds

13
Sorted list using Heap sort: [13, 16, 34, 39, 43, 59, 72, 72, 89, 98]
Time taken by Heap sort: 0.000031 seconds

Do you want to sort a list? (y/n): y


Enter the number of values in the list: 8
Enter a value for the list: 56
Enter a value for the list: 87
Enter a value for the list: 23
Enter a value for the list: 89
Enter a value for the list: 53
Enter a value for the list: 99
Enter a value for the list: 27
Enter a value for the list: 77
Sorted list using Insertion sort: [23, 27, 53, 56, 77, 87, 89, 99]
Time taken by Insertion sort: 0.000016 seconds
Sorted list using Heap sort: [23, 27, 53, 56, 77, 87, 89, 99]
Time taken by Heap sort: 0.000061 seconds

Do you want to sort a list? (y/n): y


Enter the number of values in the list: 6
Enter a value for the list: 23
Enter a value for the list: 99
Enter a value for the list: 46
Enter a value for the list: 83
Enter a value for the list: 57
Enter a value for the list: 92
Sorted list using Insertion sort: [23, 46, 57, 83, 92, 99]
Time taken by Insertion sort: 0.000017 seconds
Sorted list using Heap sort: [23, 46, 57, 83, 92, 99]
Time taken by Heap sort: 0.000025 seconds
Do you want to sort a list? (y/n): n

RESULT:
Thus, the program has been executed successfully.

14
Ex.No: 5
GRAPH TRAVERSAL - BREADTH FIRST SEARCH
Date:

AIM:

To implement graph traversal using Breadth First Search.

ALGORITHM:

Step 1: Start.
Step 2: Put any one of the graph’s vertices at the back of the queue.
Step 3: Take the front item of the queue and add it to the visited list.
Step 4: Create a list of that vertex's adjacent nodes. Add those which are not within the visited list tothe rear of
the queue.
Step 5: Keep continuing steps two and three till the queue is empty.
Step 6: Stop.
PROGRAM:

from collections import deque


# Define the Graph class
class Graph:
def __init__(self):
self.graph = {}

# Add edge to the graph


def add_edge(self, u, v):
if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)

# Perform BFS on the graph


def bfs(self, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:

15
visited.add(node)
print(node, end=' ')
if node in self.graph:
for neighbour in self.graph[node]:
queue.append(neighbour)
# Get graph input from the user
g = Graph()
n = int(input("Enter the number of edges: "))
for i in range(n):
u, v = input("Enter edge {}: ".format(i+1)).split()
g.add_edge(u,v)

# Get starting node input from the user


start = input("Enter the starting node: ")

# Perform BFS traversal


print("BFS Traversal starting from node {}:".format(start))
g.bfs(start)

OUTPUT:

Enter the number of edges: 6


Enter edge 1: A B
Enter edge 2: A C
Enter edge 3: B D
Enter edge 4: B E
Enter edge 5: C F
Enter edge 6: C G
Enter the starting node: A
BFS Traversal starting from node A:
ABCDEFG

RESULT:

Thus, graph traversal using Breadth First Search has been implemented successfully.

16
Ex.No: 6
GRAPH TRAVERSAL - DEPTH FIRST SEARCH
Date:

AIM:

To implement graph traversal using Depth First Search.

ALGORITHM:

Step 1: Start.
Step 2: Put any one of the graph's vertex on top of the stack.
Step 3: Take the top item of the stack and add it to the visited list of the vertex.
Step 4: Create a list of that adjacent node of the vertex. Add the ones which aren't in the visited list of
vertexes to the top of the stack.
Step 5: Keep repeating steps 2 and 3 until the stack is empty.
Step 6: Stop.
PROGRAM:

# Define the Graph class


class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)

def dfs(self, start, visited=None):


if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
if start in self.graph:
for neighbour in self.graph[start]:
if neighbour not in visited:
self.dfs(neighbour, visited)

# Get graph input from the user


g = Graph()
n = int(input("Enter the number of edges: "))
for i in range(n):
u, v = input("Enter edge {}: ".format(i+1)).split()
g.add_edge(u,v)

17
# Get starting node input from the user
start = input("Enter the starting node: ")

# Perform DFS traversal


print("DFS Traversal starting from node {}:".format(start))
g.dfs(start)

OUTPUT:

Enter the number of edges: 6


Enter edge 1: A B
Enter edge 2: A C
Enter edge 3: B D
Enter edge 4: B E
Enter edge 5: C F
Enter edge 6: C G
Enter the starting node: A
DFS Traversal starting from node A:
ABDECFG

RESULT:

Thus, graph traversal using Depth First Search has been implemented successfully.

18
Ex.No: 7
IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
Date:

AIM:

To implement a python program to find the shortest paths to other vertices using dijkstra’s algorithm.

ALGORITHM:
Step 1: Start.
Step 2: Mark all vertex as unvisited.
Step 3: Mark source vertex as 0 and other vertex as infinity.
Step 4: Calculate the path length of all neighbor nodes from current adding the weight of
edges.
Step 5: Now new path is smaller than previous path then replace it.
Step 6: Mark the current vertex as visited after moving to its neighbor.
Step 7: Choose the path which is having smallest path length and go to step 3.
Step 8: Repeat the steps until all vertices are visited.
Step 9: Stop.
PROGRAM:
import heapq
def dijkstra(graph, start):
# Initialize distances to all nodes as infinity except the starting node
distances = {node: float('inf') for node in graph}
distances[start] = 0
# Use a priority queue to keep track of the next closest node to visit
pq = [(0, start)]
while pq:
# Get the node with the smallest distance from the start
current_dist, current_node = heapq.heappop(pq)
# If we've already visited this node with a shorter distance, skip it
if current_dist > distances[current_node]:
continue

# For each neighbor of the current node, calculate the new distance
for neighbor, weight in graph[current_node].items():

19
new_dist = current_dist + weight
# If the new distance is shorter than the current distance, update it
if new_dist < distances[neighbor]:
distances[neighbor] = new_dist
heapq.heappush(pq, (new_dist, neighbor))
return distances

# Ask the user to input the graph as a list of edges


edges = input("Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): ").split()
graph = {}
for edge in edges:
node1, node2, weight = edge.split(',')
weight = int(weight)
if node1 not in graph:
graph[node1] = {}
if node2 not in graph:
graph[node2] = {}
graph[node1][node2] = weight
graph[node2][node1] = weight # since it's an undirected graph

# Ask the user to input the starting node


start = input("Enter the starting node: ")
# Use Dijkstra's algorithm to find the shortest path from the starting node to all other nodes
distances = dijkstra(graph, start)

# Print the result


print("Shortest distances from node {} to all other nodes:".format(start))
for node, dist in distances.items():
print("{}: {}".format(node, dist))

20
OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): A,B,4 A,C,5 B,C,11 B,E,7
B,D,9 C,E,3 D,E,13 D,F,2 E,F,6

Enter the starting node: A


Shortest distances from node A to all other nodes:
A: 0
B: 4
C: 5
E: 8
D: 13
F: 14

RESULT:

Thus, the implementation of dijkstra’s algorithm has been executed successfully.

21
Ex.No: 8
IMPLEMENTATION OF PRIMS ALGORITHM
Date:

AIM:

To implement the prim’s algorithm for undirected graph.

ALGORITHM:

Step 1: Start

Step 2: Initialize an empty MST.

Step 3: Choose any vertex v to start with.

Step 4: Create a priority queue Q and add all edges incident to v to Q, with their weights as keys.

Step 5: Mark v as visited.

Step 6: While Q is not empty:

i. Remove the edge with minimum weight from Q.

ii. If both vertices of the edge are visited, ignore the edge and continue to the next one.

Iii. Otherwise, mark the unvisited vertex as visited, add the edge to the MST, and add all edges incident
to the new vertex to Q.

Step 7: Return the MST.

Step 8: Stop

PROGRAM:
import heapq

def prims(graph, start):


# Initialize the set of visited nodes and the set of unvisited nodes
visited = set()
unvisited = set(graph.keys())

# Initialize the dictionary that will keep track of the shortest edge to each node
shortest_edges = {node: (float('inf'), None) for node in graph}
shortest_edges[start] = (0, start)

22
# Use a priority queue to keep track of the next closest edge to visit
pq = [(0, start)]

while unvisited:
# Get the edge with the smallest weight
current_weight, current_node = heapq.heappop(pq)

# If we've already visited this node, skip it


if current_node in visited:
continue

# Mark the current node as visited and remove it from the set of unvisited nodes
visited.add(current_node)
unvisited.remove(current_node)

# For each neighbor of the current node, update the shortest edge to that neighbor
for neighbor, weight in graph[current_node].items():
if neighbor not in unvisited:
continue
if weight < shortest_edges[neighbor][0]:
shortest_edges[neighbor] = (weight, current_node)
heapq.heappush(pq, (weight, neighbor))

# Print the sum of the shortest distance and the shortest path to each node
print("Sum of the shortest distance and the shortest path to each node:")
for node in shortest_edges:
distance = shortest_edges[node][0]
path = []
while node != start:
path.insert(0, node)
node = shortest_edges[node][1]
path.insert(0, start)
print("{}: {} ({})".format(node, distance, "->".join(path)))

23
# Ask the user to input the graph as a list of edges
edges = input("Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): ").split()
graph = {}
for edge in edges:
node1, node2, weight = edge.split(',')
weight = int(weight)
if node1 not in graph:
graph[node1] = {}
if node2 not in graph:
graph[node2] = {}
graph[node1][node2] = weight
graph[node2][node1] = weight # since it's an undirected graph

# Ask the user to input the starting node


start = input("Enter the starting node: ")

# Use Prim's algorithm to find the shortest distance and path to each node in the graph
prims(graph, start)

OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): A,B,4 A,C,4 B,C,2 C,D,3 C,E,2
C,F,4 D,F,3 E,F,3
Enter the starting node: A
Sum of the shortest distance and the shortest path to each node:
A: 0 (A)
A: 4 (A->B)
A: 2 (A->B->C)
A: 3 (A->B->C->D)
A: 2 (A->B->C->E)
A: 3 (A->B->C->E->F)

RESULT:

Thus the program was implemented successfully.

24
Ex.No: 9 IMPLEMENT FLOYD’S ALGORITHM FOR THE ALL-PAIRS

Date: SHORTEST-PATHS PROBLEM

AIM:

To implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.

ALGORITHM:

Step 1:Start

Step 2: Consider the intermediate nodes.

Step 3: Traverse through each of the intermediates i.e from vertex to destination.

Step 4: Once all the nodes are traversed, compare and select the shortest path.

Step 5: End

PROGRAM:
def floyd(graph):
# Create a copy of the graph dictionary to avoid modifying the original
graph = graph.copy()

# Add missing nodes to the graph with infinite distance to themselves


nodes = set(graph.keys())
for i in nodes:
for j in nodes:
if j not in graph[i]:
graph[i][j] = float('inf')
graph[i][i] = 0

# Perform Floyd's algorithm


for k in nodes:
for i in nodes:
for j in nodes:

25
if graph[i][j] > graph[i][k] + graph[k][j]:
graph[i][j] = graph[i][k] + graph[k][j]

# Return the shortest paths as a dictionary of dictionaries


return graph

# Get the input from the user


edges = input("Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): ")
edges = edges.split()
graph = {}
for edge in edges:
start, end, weight = edge.split(',')
if start not in graph:
graph[start] = {}
graph[start][end] = int(weight)

# Find the shortest paths using Floyd's algorithm


paths = floyd(graph)

# Print the shortest paths


print("Shortest paths:")
for start in sorted(paths.keys()):
for end in sorted(paths[start].keys()):
if paths[start][end] == float('inf'):
print(f"{start} -> {end}: No path")
else:
print(f"{start} -> {end}: {paths[start][end]}")

26
OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): 0,2,-2 1,0,4 1,2,3
2,3,2 3,1,-1
Shortest paths:
0 -> 0: 0
0 -> 1: -1
0 -> 2: -2
0 -> 3: 0
1 -> 0: 4
1 -> 1: 0
1 -> 2: 2
1 -> 3: 4
2 -> 0: 5
2 -> 1: 1
2 -> 2: 0
2 -> 3: 2
3 -> 0: 3
3 -> 1: -1
3 -> 2: 1
3 -> 3: 0

RESULT:

The program to implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problemhas been executed
successfully.

27
Ex.No: 10
WARSHALL ALGORITHM
Date:

AIM:

To write a python program to compute the transitive closure of a given directed graph using Warshall's
algorithm.

ALGORITHM:

Step 1: Start

Step 2: Define transitive_closure function with the steps involved in warshall.

Step 3: Declare the graph variable in matrix form

Step 4: Pass the variable as paramater to the defined function

Step 5: Print the output

Step 6: Stop

PROGRAM:
def transitive_closure(graph):
n = len(graph)
tc = [[0] * n for _ in range(n)]

for i in range(n):
for j in range(n):
tc[i][j] = graph[i][j]

for k in range(n):
for i in range(n):
for j in range(n):
tc[i][j] = tc[i][j] or (tc[i][k] and tc[k][j])

return tc

# Take user input for adjacency matrix of directed graph

28
n = int(input("Enter number of vertices: "))
graph = []
for i in range(n):
row = list(map(int, input(f"Enter row {i+1}: ").split()))
graph.append(row)

# Compute transitive closure using Warshall's algorithm


tc = transitive_closure(graph)

# Print the transitive closure matrix


print("Transitive Closure:")
for row in tc:
print(row)
OUTPUT:
Enter number of vertices: 4
Enter row 1: 0 1 0 0
Enter row 2: 0 0 0 1
Enter row 3: 0 0 0 0
Enter row 4: 1 0 1 0
Transitive Closure:
[1, 1, 1, 1]
[1, 1, 1, 1]
[0, 0, 0, 0]
[1, 1, 1, 1]

RESULT:

Thus the program to implement warshall algorithm was implemented succussfully.

29
Ex.No: 11
DIVIDE AND CONQUER TECHNIQUE
Date:

AIM:

To write a python program to find out the maximum and minimum numbers in a given list of n numbers
using the divide and conquer technique.

ALGORITHM:

Step 1 : Start.

Step 2 : Define a function called max_min that takes a list of numbers as input.

Step 3 : If the length of the input list is 1, return a tuple with the single number as both the maximum
and minimum value.

Step 4 : If the length of the input list is 2, compare the two numbers and return a tuple with the
maximum and minimum values.

Step 5 : If the length of the input list is greater than 2, split the list in half and recursively call the
max_min function on each half.

Step 6 : For each recursive call, store the maximum and minimum values of the left half and the
maximum and minimum values of the right half in separate variables.

Step 7 : Compare the maximum values of the left and right halves, and return the larger value as the
maximum value for the entire list.

Step 8 : Compare the minimum values of the left and right halves, and return the smaller value as the
minimum value for the entire list.

Step 9 : Call the max_min function on the entire input list, and print the maximum and minimum values
returned by the function.

Step 10 : Stop.

PROGRAM:
def max_min(nums):
if len(nums) == 1:
return (nums[0], nums[0])
elif len(nums) == 2:

30
return (max(nums[0], nums[1]), min(nums[0], nums[1]))
else:
mid = len(nums) // 2
left_max, left_min = max_min(nums[:mid])
right_max, right_min = max_min(nums[mid:])
return (max(left_max, right_max), min(left_min, right_min))

# prompt user for input


input_str = input("Enter a list of numbers separated by spaces: ")
nums = [int(num) for num in input_str.split()]

# call max_min function and print results


max_num, min_num = max_min(nums)
print("Max number:", max_num)
print("Min number:", min_num)
OUTPUT:
Enter a list of numbers separated by spaces: 34 53 6 87 2 45 98 76
Max number: 98
Min number: 2

RESULT:

Thus the program to find out the maximum and minimum numbers in a given list of n numbers using the
divide and conquer technique was implemented succussfully.

31
Ex.No: 12
MERGE SORT & QUICK SORT
Date:

AIM:
To write a program to sort a given set of elements using merge sort and quick sort and to determine time
requited for sorting pot a graph of time taken vs n.

ALGORITHM:

Step 1 : Start

Step 2 : Define a function for merge sort that recursively divides a list into smaller sublists and merges
them together in sorted order.

Step 3 : Define a function for quick sort that recursively partitions a list into two sublists based on a
pivot value, and sorts each sublist separately.

Step 4 : Initialize empty lists to store values of n and time taken for each algorithm.

Step 5 : Prompt the user for permission to perform multiple sorting operations using a while loop.

Step 6 : Get input from the user for the number of values in the list and the values themselves.

Step 7 : Measure time for merge sort and quick sort using the time.perf_counter() function.

Step 8 : Append the time taken by each algorithm to their respective lists.

Step 9 : Store the value of n in a list.

Step 10:Print the sorted list and the time taken by each algorithm and Plot the graph of time taken versus
n for each algorithm using matplotlib.pyplot.

Step 11: Stop.

PROGRAM:
import time
import matplotlib.pyplot as plt
# merge sort
def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]

32
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]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


lst[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


lst[k] = right_half[j]
j += 1
k += 1
# quick sort
def quick_sort(lst):
if len(lst) <= 1:
return lst
else:
pivot = lst.pop()
greater = []
lesser = []
for item in lst:
if item > pivot:

33
greater.append(item)
else:
lesser.append(item)
return quick_sort(lesser) + [pivot] + quick_sort(greater)

# Initialize lists to store values of n and time taken for each algorithm
n_values = []
merge_sort_times = []
quick_sort_times = []

# Prompt the user for permission to perform multiple sorting operations


while True:
choice = input("Do you want to sort a list? (y/n): ")
if choice.lower() != 'y':
break

# Get input from the user


n = int(input("Enter the number of values in the list: "))
lst = []
for i in range(n):
val = int(input("Enter a value for the list: "))
lst.append(val)

# Measure time for merge sort and quick sort


start_time = time.perf_counter()
merge_sort(lst)
end_time = time.perf_counter()
merge_sort_time = end_time - start_time
merge_sort_times.append(merge_sort_time)

start_time = time.perf_counter()
quick_sort(lst)
end_time = time.perf_counter()

34
quick_sort_time = end_time - start_time
quick_sort_times.append(quick_sort_time)

# Store the value of n


n_values.append(n)

# Print the sorted list and the time taken by each algorithm
print("Sorted list using merge sort:", lst)
print("Time taken by merge sort: {:.6f} seconds".format(merge_sort_time))
print("Sorted list using quick sort:", lst)
print("Time taken by quick sort: {:.6f} seconds".format(quick_sort_time))

# Plot the graph of time taken versus n for each algorithm


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 taken (seconds)')
plt.title('Sorting algorithms')
plt.legend()
plt.show()
OUTPUT:
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 6
Enter a value for the list: 34
Enter a value for the list: 87
Enter a value for the list: 95
Enter a value for the list: 99
Enter a value for the list: 34
Enter a value for the list: 12
Sorted list using merge sort: [12, 34, 34, 87, 95]
Time taken by merge sort: 0.000027 seconds
Sorted list using quick sort: [12, 34, 34, 87, 95]
Time taken by quick sort: 0.000013 seconds

35
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 8
Enter a value for the list: 23
Enter a value for the list: 76
Enter a value for the list: 98
Enter a value for the list: 45
Enter a value for the list: 33
Enter a value for the list: 12
Enter a value for the list: 45
Enter a value for the list: 27
Sorted list using merge sort: [12, 23, 27, 33, 45, 45, 76]
Time taken by merge sort: 0.000028 seconds
Sorted list using quick sort: [12, 23, 27, 33, 45, 45, 76]
Time taken by quick sort: 0.000018 seconds
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 9
Enter a value for the list: 54
Enter a value for the list: 98
Enter a value for the list: 56
Enter a value for the list: 24
Enter a value for the list: 10
Enter a value for the list: 85
Enter a value for the list: 36
Enter a value for the list: 29
Enter a value for the list: 78
Sorted list using merge sort: [10, 24, 29, 36, 54, 56, 78, 85]
Time taken by merge sort: 0.000035 seconds
Sorted list using quick sort: [10, 24, 29, 36, 54, 56, 78, 85]
Time taken by quick sort: 0.000017 seconds
Do you want to sort a list? (y/n): n
RESULT:
Thus, the program has been executed successfully.

36
Ex.No: 13
N-QUEEN PROBLEM
Date:

AIM:
To write a program to Implement N Queens problem using Backtracking.

ALGORITHM:
Step 1 : Start.
Step 2 : Initialize an empty NxN chessboard.
Step 3 : Start with the first row (row 0).
Step 4 : Try to place a queen in each column of the current row, one by one.
Step 5 : For each column, check if it's safe to place the queen at the current position.
Step 6 : If it's safe, mark the current cell as occupied by a queen, and move to the next row (row 1).
Step 7 : Repeat steps 3-5 recursively for each row until all N queens are placed on the board.
Step 8 : If all N queens are successfully placed, print the board as the solution.
Step 9 : If it's not possible to place a queen in any column of the current row, backtrack to the previous
row and try to place the queen in a different column.
Step 10 : If all columns of all rows have been tried and no solution is found, return "No solution exists".
Step 11 : Stop.
PROGRAM:
def is_safe(board, row, col, n):
for i in range(row):
if board[i][col] == 1:
return False
i = row
j = col
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1
i = row
j = col
while i >= 0 and j < n:

37
if board[i][j] == 1:
return False
i -= 1
j += 1
return True
def solve_n_queens(board, row, n):
if row == n:
return True
for col in range(n):
if is_safe(board, row, col, n):
board[row][col] = 1
if solve_n_queens(board, row + 1, n):
return True
board[row][col] = 0
return False
def print_board(board):
for row in board:
print(" ".join(str(cell) for cell in row))
n = int(input("Enter the value of N: "))
board = [[0 for x in range(n)] for y in range(n)]
if solve_n_queens(board, 0, n):
print_board(board)
else:
print("No solution found")
OUTPUT:
Enter the value of N: 4
0100
0001
1000
0010
RESULT:
Thus, the program for n-Queen problem using backtracking has been executed successfully.

38
Ex.No: 14
TRAVELLING SALESMAN PROBLEM
Date:

AIM:
To write a program to find the optimal solution for the Traveling Salesperson problem and then solve the
same problem instance using any approximation algorithm and determine the error in the approximation.

ALGORITHM:
Step 1 : Start.
Step 2 : Given a complete undirected graph G with n vertices and edge weights w(i,j), construct a
minimum spanning tree T of G.
Step 3 : Let O be the set of vertices with odd degree in T.
Step 4 : Compute a minimum-weight perfect matching M on the vertices in O.
Step 5 : Combine the edges in T and M to form a connected graph H.
Step 6 : Find an Eulerian tour in H, i.e., a cycle that traverses each edge exactly once.
Step 7 : Convert the Eulerian tour into a Hamiltonian tour by skipping repeated vertices, i.e., vertices
that have already been visited.
Step 8 : Output the resulting Hamiltonian tour as the solution to the TSP problem.
Step 9 : Stop.
PROGRAM:
import sys

def least_opt(c):
global cost_opt
nc = sys.maxsize
min = sys.maxsize
kmin = sys.maxsize
for i in range(0, n):
if a[c][i] != 0 and visit[i] == 0:
if a[c][i] < min:
min = a[c][i]
kmin = a[c][i]
nc = i
if kmin != sys.maxsize:

39
cost_opt += kmin
return nc

def least_apr(c):
global cost_apr
nc = sys.maxsize
min = sys.maxsize
kmin = sys.maxsize
for i in range(0, n):
if a[c][i] != 0 and visit[i] == 0:
if a[c][i] < kmin:
min = a[c][i]
kmin = a[c][i]
nc = i
if kmin != sys.maxsize:
cost_apr += kmin
return nc

def mincost_opt(city):
global cost_opt
visit[city] = 1
print(city, end='-->')
ncity = least_opt(city)
if ncity == sys.maxsize:
ncity = 0
print(ncity)
cost_opt += a[city][ncity]
return
mincost_opt(ncity)

def mincost_apr(city):
global cost_apr
visit[city] = 1

40
print(city, end='-->')
ncity = least_apr(city)
if ncity == sys.maxsize:
ncity = 0
print(ncity)
cost_apr += a[city][ncity]
return
mincost_apr(ncity)

n = int(input("Enter No. of cities: "))


a = [[0] * n for i in range(n)]
visit = [0] * n
cost_opt = 0
cost_apr = 0
print("Enter the cost matrix:")
for i in range(0, n):
print("Enter elements of row %d:" % i)
row = input().split()
for j in range(0, n):
a[i][j] = int(row[j])
print("The cost list is:")
for i in range(0, n):
print()
for j in range(0, n):
print("\t%d" % a[i][j], end='')

print("\nOptimal Solution:")
print("The path is:")
mincost_opt(0)
print("Minimum cost: %d" % cost_opt)
visit = [0] * n
print("\nApproximated Solution:")
print("The path is:")

41
mincost_apr(0)
print("Minimum cost: %d" % cost_apr)
print("Error in approximation is approximated solution/optimal solution = %f" % (cost_apr/cost_opt))
OUTPUT:
Enter No. of cities: 4
Enter the cost matrix:
Enter elements of row 0:
0 10 15 20
Enter elements of row 1:
10 0 35 25
Enter elements of row 2:
15 35 0 30
Enter elements of row 3:
20 25 30 0
The cost list is:
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
Optimal Solution:
The path is:
0-->1-->3-->2-->0
Minimum cost: 80

Approximated Solution:
The path is:
0-->1-->3-->2-->0
Minimum cost: 80
Error in approximation is approximated solution/optimal solution = 1.000000

RESULT:
Thus, the program has been executed successfully.

42
Ex.No: 15
RANDOMISED ALGORITHM TO FIND KTH SMALLEST ELEMENT
Date:

AIM:
To write a program to Implement randomized algorithms for finding the kth smallest number

ALGORITHM:
Step 1 : Start.
Step 2 : If the length of the input array arr is 1, return the only element in the array as the k-th smallest
element.
Step 3 : Choose a random element pivot from the input array arr.
Step 4 : Partition the array arr into three parts: lows, pivots, and highs.
*lows: a list of elements in arr that are less than pivot
*pivots: a list of elements in arr that are equal to pivot
*highs: a list of elements in arr that are greater than pivot
Step 5 : If k is less than the length of lows, the k-th smallest element must be in the lows list.
Recursively call quick_select with lows and k as inputs.
Step 6 : If k is less than the length of lows plus the length of pivots, the k-th smallest element is the pivot.
Return the pivot as the result.
Step 7 : If k is greater than the length of lows plus the length of pivots, the k-th smallest element must be
in the highs list. Recursively call quick_select with highs and k - len(lows) - len(pivots) as inputs.
Step 8 : Return the result of the recursive call to quick_select.
Step 9 : Stop.
PROGRAM:
import random
def quick_select(arr, k):
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
lows = [x for x in arr if x < pivot]
highs = [x for x in arr if x > pivot]
pivots = [x for x in arr if x == pivot]
if k < len(lows):
return quick_select(lows, k)

43
elif k < len(lows) + len(pivots):
return pivots[0]
else:
return quick_select(highs, k - len(lows) - len(pivots))
arr = list(map(int, input("Enter array elements separated by space: ").split()))
k = int(input("Enter the value of k: "))
kth_smallest = quick_select(arr, k-1)
print(f"The {k}th smallest number in the array is: {kth_smallest}")

OUTPUT:

Enter array elements separated by space: 34 23 65 74 12 16 76 23 98

Enter the value of k: 4

The 4th smallest number in the array is: 23

RESULT:
Thus, the program to Implement randomized algorithms for finding the kth smallest number has been
executed successfully.

44

You might also like