You are on page 1of 37

TABLE OF CONTENTS

SL. DATE NAME OF THE EXPERIMENT PAGE SIGN


NO NO

1. Implement Linear Search. Determine the time required 5


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
2. Implement recursive Binary Search. Determine the 8
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.
3. Given a text txt [0...n-1] and a pattern pat [0...m-1], 11
write a function search (char pat [ ], char txt [ ]) that
prints all occurrences of pat [ ] in txt [ ]. You may
assume that n > m.

4. Sort a given set of elements using the Insertion sort 13


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.
5. 17
Develop a program to implement graph traversal using
Breadth First Search

6. 19
Develop a program to implement graph traversal using
Depth First Search

7. From a given vertex in a weighted connected graph, 21


develop a program to find the shortest paths to other
vertices using Dijkstra’s algorithm
8. Find the minimum cost spanning tree of a given 23
undirected graph using Prim’s algorithm.

3
9. Implement Floyd’s algorithm for the All-Pairs- 26
Shortest-Paths problem

10. Compute the transitive closure of a given directed 28


graph using Warshall's algorithm.

11. Develop a program to find out the maximum and 30


minimum numbers in a given list of n numbers using
the divide and conquer technique.

12. Implement Merge sort and Quick sort methods to sort 33


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.

13. Implement N Queens problem using Backtracking. 37

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.

Step 3: Match the key with arr[i].

Step 4: If the key matches, return the index. Otherwise, increment i by 1.

PROGRAM:

import time

import random

import matplotlib.pyplot as plt

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:

arr = [random.randint(0,n) for i in range(n)]

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:

print(f"n={n}:Element is present at index{result}")

else:

print(f"n={n}:Element is not present in array")

print(f"Timetaken:{end_time - start_time}\n")

plt.plot(n_values,times)

plt.xlabel("n")

plt.ylabel("Time taken")

plt.show()

OUTPUT:

n=10:Element is not present in array

Timetaken:0.0

n=100:Element is not present in array

Timetaken:0.0

n=500:Element is present at index292

Timetaken:0.0

n=550:Element is present at index43

Timetaken:0.0

n=600:Element is not present in array

Timetaken:0.0

n=700:Element is present at index162

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 1: Start searching data from middle of the list.

Step 2: If it is a match, return the index of the item, and exit.

Step 3: If it is not a match, probe position.

Step 4: Divide the list using probing formula and find the new midle.

Step 5: If data is greater than middle, search in higher sub-list.

Step 6: If data is smaller than middle, search in lower sub-list.

Step 7: Repeat until match.

PROGRAM:

import time

import random

import matplotlib.pyplot as plt

def binary_search(arr,left,right,x):

if right >= left:

mid = left + (right - left) // 2

if arr[mid] == x:

return mid

elif arr[mid] > x:

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:

arr = [random.randint(0,n)for _ in range(n)]

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:

print(f"n={n}:Element is present at index{result}")

else:

print(f"n={n}:Element is not present in array")

print(f"Timetaken:{end_time - start_time}\n")

plt.plot(n_values,times)

plt.xlabel("n")

plt.ylabel("Time taken")

plt.show()

9
OUTPUT:

n=10:Element is present at index1

Timetaken:0.0

n=100:Element is not present in array

Timetaken:0.0

n=500:Element is not present in array

Timetaken:0.0

n=550:Element is not present in array

Timetaken:0.0

n=600:Element is not present in array

Timetaken:0.0

n=700:Element is not present in array

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 1: Let the text be T and the pattern be P.

Step 2: Initialize an empty list to store the positions where the pattern is found.

Step 3: For each position i in T:

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.

Step 4: Return the list of matches.

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)

if __name__ == '__main__':

11
txt = "AABAACAADAABAAABAA"

pat = "AABA"

search(pat, txt)

OUTPUT:

Pattern Found at index 0

Pattern Found at index 9

Pattern Found at index 13

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 2: The variable ‘n’ is assigned the length of the array A.

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 2: Build a heap from the given input array.

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

while j>=0 and key < arr[j]:

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

if l < n and arr[largest] < arr[l]:

largest = l

if r < n and arr[largest] < arr[r]:

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):

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:

arr = [random.randint(1,1000) for _ in range(n)]

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)

import matplotlib.pyplot as plt

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.ylabel("Time taken (seconds)")

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

Date: Develop a program to implement graph traversal using Breadth First


Search

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:

from collections import deque

graph ={ "A": ['B','C'],

'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]:

if neighbor not in visited:

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

Date: Develop a program to implement graph traversal using Depth First


Search

AIM:

To write a python program to Develop a program to implement graph traversal using Depth First
Search.

ALGORITHM:

Step 1: Consider the graph you want to navigate.

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.

Visited array(size of the graph)

Queue data structure

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()

if node not in visited:

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:

{'C', 'A', 'E', 'D', 'F', 'B'}

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

Date: From a given vertex in a weighted connected graph, develop a program


to find the shortest paths to other vertices using Dijkstra’s algorithm.

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

def dijkstra(graph, start):

distances = {node: float('inf') for node in graph}

distances[start] = 0

pq = [(0, start)]

while pq:

(dist, curr_node) = heapq.heappop(pq)

for (adj_node, weight) in graph[curr_node].items():

21
new_dist = dist + weight

if new_dist < distances[adj_node]:

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:

{'A': 0, 'B': 3, 'C': 3, 'D': 2}

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:

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as
fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

PROGRAM:

import sys

class Graph():

def __init__(self, vertices):

self.V = vertices

self.graph = [[0 for column in range(vertices)]for row in range(vertices)]

def printMST(self, parent):

print("Edge \tWeight")

for i in range(1, self.V):

print(parent[i], '-',i,'\t',self.graph[i][parent[i]])

def minKey(self, key, mstSet):

23
min = sys.maxsize

for v in range(self.V):

if key[v] < min and mstSet[v] == False:

min = key[v]

min_index = v

return min_index

def primMST(self):

key = [sys.maxsize] * self.V

parent = [None] * self.V

key[0] = 0

mstSet = [False] * self.V

parent[0] = -1

for cout in range(self.V):

u = self.minKey(key, mstSet)

mstSet[u] = True

for v in range(self.V):

if self.graph[u][v] > 0 and mstSet[v] == False:

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

Date: Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem

AIM:

To write a python program to implement Floyd’s algorithm for the All-Pairs- Shortest-Paths
problem.

ALGORITHM:

Step 1: Initialize two-pointers and start traversing the linked list.

Step 2: Move the slow pointer by one position.

Step 3: Move the fast pointer by two positions.

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):

dist = list(map(lambda i: list(map(lambda j: j, i)), graph))

for k in range(V):

for i in range(V):

for j in range(V):

dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j])

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:

print("%7d\t" % (dist[i][j]), end=' ')

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

INF INF INF 0

RESULT:

Thus the python program to implement Floyd’s algorithm for the All-Pairs- Shortest-Paths
problem.

27
Ex.No:10

Date: Compute the transitive closure of a given directed graph using


Warshall's algorithm

AIM:

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

ALGORITHM:

Step 1: Initialize two-pointers and start traversing the linked list.

Step 2: Move the slow pointer by one position.

Step 3: Move the fast pointer by two positions.

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:

from collections import defaultdict

class Graph():

def __init__(self, vertices):

self.V = vertices

def printSolution(self, reach):

print("Following Matrix transitive closure of the given grpah")

for i in range(self.V):

for j in range(self.V):

if (i == j):

print("%7d\t" % (1),end= " ")

else:

print("%7d\t" %(reach[i][j]),end = " ")

print()

28
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):

reach[i][j] = reach[i][j] or (reach[i][j] and reach[k][j])

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:

Following Matrix transitive closure of the given grpah

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:

def divideandConquer_Max(arr, ind, len):

maximum = -1

if ind >= len -2:

if arr[ind] > arr[ind +1]:

return arr[ind]

else:

return arr[ind + 1]

30
maximum = divideandConquer_Max(arr, ind + 1, len)

if arr[ind] > maximum:

return arr[ind]

else:

return maximum

def divideandConquer_Min(arr, ind,len):

minimum = 0

if ind >= len-2:

if arr[ind] < arr[ind + 1]:

return arr[ind]

else:

return arr[ind + 1]

minimum = divideandConquer_Min(arr, ind+1, len)

if arr[ind] < minimum:

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)

print("The minimum number in the array is:", minimum)

print("The maximum number in the array is:", maximum)

31
OUTPUT:

The minimum number in the array is: 1

The maximum number in the array is: 90

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

Step 1: if it is only one element in the list it is already sorted, return.


Step 2: divide the list recursively into two halves until it can no more be divided.
Step 3: merge the smaller lists into new list in sorted order.
Quick Sort
Step 1: Choose the highest index value has pivot
Step 2: Take two variables to point left and right of the list excluding pivot
Step 3: left points to the low index
Step 4: right points to the high
Step 5: while value at left is less than pivot move right
Step 6: while value at right is greater than pivot move left
Step 7: if both step 5 and step 6 does not match swap left and right
Step 8: if left ≥ right, the point where they met is new pivot
PROGRAM:

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)

def merge(left, right):

result = []

i=j=0

while i < len(left) and j < len(right):

if left[i] < right[j]:

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]

left = [x for x in arr[1:] if x <= pivot]

right = [x for x in arr[1:] if x > pivot]

return quick_sort(left) + [pivot] + quick_sort(right)

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_time = time.time() - start_time

merge_sort_times.append(merge_sort_time)

start_time = time.time()

sorted_arr = quick_sort(arr)

quick_sort_time = time.time() - start_time

quick_sort_times.append(quick_sort_time)

print(f"n = {n}: Merge sort time = {merge_sort_time:.6f}s,Quick sort time = {quick_sort_time:.6f}s")

import matplotlib.pyplot as plt

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:

n = 10: Merge sort time = 0.000000s,Quick sort time = 0.000000s

n = 100: Merge sort time = 0.000000s,Quick sort time = 0.000000s

n = 1000: Merge sort time = 0.015627s,Quick sort time = 0.000000s

n = 10000: Merge sort time = 0.062504s,Quick sort time = 0.062509s

n = 100000: Merge sort time = 0.937566s,Quick sort time = 1.640747s

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

Date: Implement N Queens problem using Backtracking.

AIM:

To write a python program to implement N Queens problem using Backtracking.

ALGORITHM:

Step 1: Initialize an empty chessboard of size NxN.

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 5: If all N queens have been placed, print the solution.

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(board[i][j], end = ' ' )

print()

def isSafe(board, row, col):

for i in range(col):

if board[row][i] == 1:

37
return False

for i,j in zip(range(row, -1, -1),range(col, -1, -1)):

if board[i][j] == 1:

return False

for i,j in zip(range(row, N, 1),range(col, -1, -1)):

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

if solveNQUtil(board, col+1) == True:

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:

print("Solution does not exist")

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

You might also like