0% found this document useful (0 votes)
20 views49 pages

Algorithms Lab

The document provides a series of programming exercises covering various algorithms including Linear Search, Binary Search, Pattern Searching, Insertion Sort, Heap Sort, Breadth First Search, Depth First Search, Dijkstra's Algorithm, Prim's Algorithm, Floyd's Algorithm, and Merge Sort. Each section includes the aim, algorithm, program code, and output examples demonstrating the functionality of the algorithms. The document serves as a practical guide for implementing and understanding these fundamental algorithms in programming.

Uploaded by

Mohan Raj
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)
20 views49 pages

Algorithms Lab

The document provides a series of programming exercises covering various algorithms including Linear Search, Binary Search, Pattern Searching, Insertion Sort, Heap Sort, Breadth First Search, Depth First Search, Dijkstra's Algorithm, Prim's Algorithm, Floyd's Algorithm, and Merge Sort. Each section includes the aim, algorithm, program code, and output examples demonstrating the functionality of the algorithms. The document serves as a practical guide for implementing and understanding these fundamental algorithms in programming.

Uploaded by

Mohan Raj
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/ 49

EX NO :

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 :

DATE: Binary Search using Recursive Function

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 :

DATE: Pattern Searching

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 :

DATE: Heap sort

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

for b in range(a-1, 0, -1):


array[b], array[0] = array[0], array[b] # swap
heapify(array, b, 0)
# Driver code
array = [ 7, 2, 5, 6, 3, 1, 8, 4]
print("The original array is:\n ", array)

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

print("The required time is:",float(end-start)

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)

g.add_edge(4, 5)print(“The BFS of the graph


is:”)g.is:”)g.bfs(2)
Output

The BFS of the graph is:

012345

Result
EX NO :
Depth First Search
DATE:

Aim

Algorithm
Program
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 dfs_util(self, vertex, visited):

visited.add(vertex)

print(vertex, end=" ")

for neighbour in self.adjacency_list[vertex]:

if neighbour not in visited:

self.dfs_util(neighbour, visited)

def dfs(self, start):

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

def dijkstra(graph, start):

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

distances[start] = 0

heap = [(0, start)]

while heap:

(current_distance, current_vertex) = heapq.heappop(heap)

if current_distance > distances[current_vertex]:

continue

for neighbor, weight in graph[current_vertex].items():

distance = current_distance + weight

if distance < distances[neighbor]:

distances[neighbor] = distance

heapq.heappush(heap, (distance, neighbor))

return distances

graph = {'A': {'B': 2, 'C': 4},

'B': {'D': 3},

'C': {'D': 1, 'E': 5},

'D': {'E': 1},

'E': {}

start_vertex = 'A'

shortest_distances = dijkstra(graph, start_vertex)

print(“The shortest distance using Dijkstra algorithm:\n”,shortest_distances)


Output
The shortest distance using Dijkstra algorithm:

{'A': 0, 'B': 2, 'C': 4, 'D': 5, 'E': 6}

Result
EX NO :

DATE: Prim’s Algorithm

Aim

Algorithm
Program
import heapq

def prim(graph):

visited = set()

minimum_spanning_tree = []

start_vertex = list(graph.keys())[0]

visited.add(start_vertex)

edges = [(weight, start_vertex, neighbor) for neighbor, weight in


graph[start_vertex].items()]

heapq.heapify(edges)

while edges:

(weight, vertex1, vertex2) = heapq.heappop(edges)

if vertex1 in visited and vertex2 in visited:

continue

minimum_spanning_tree.append((vertex1, vertex2, weight))

visited.add(vertex1 if vertex1 not in visited else vertex2)

for neighbor, weight in graph[vertex1 if vertex1 not in visited else


vertex2].items():

if neighbor not in visited:

heapq.heappush(edges, (weight, vertex1 if vertex1 not in visited else


neighbor, vertex2 if vertex2 not in visited else neighbor))

return minimum_spanning_tree

graph={'A': {'B': 2, 'C': 4},

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

'C': {'A': 4, 'D': 1, 'E': 5},

'D': {'B': 3, 'C': 1, 'E': 1},

'E': {'C': 5, 'D': 1}


}

min_spanning_tree=prim(graph)

print("The minimum spanning tree using prim's algorithm is:\n",min_spanning_tree)

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

distance_matrix = [[float('inf') if i != j else 0 for j in range(len(graph))] for i in


range(len(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)):

if distance_matrix[i][k] + distance_matrix[k][j] < distance_matrix[i][j]:

distance_matrix[i][j] = distance_matrix[i][k] + distance_matrix[k][j]

print("The shortest distance matrix is:\n",distance_matrix)

I = float('inf')

adjMatrix = [[0, I, -2, I],

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

DATE: Transitive closure using Warshall's algorithm

Aim

Algorithm
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 graph ")

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

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][k] 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 graph

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]

return (arr_max, arr_min)

elif high == low + 1:

if arr[low] > arr[high]:

arr_max = arr[low]

arr_min = arr[high]

else:

arr_max = arr[high]

arr_min = arr[low]

return (arr_max, arr_min)

else:

mid = int((low + high) / 2)

arr_max1, arr_min1 = getMinMax(low, mid, arr)

arr_max2, arr_min2 = getMinMax(mid + 1, high, arr)


return (max(arr_max1, arr_max2), min(arr_min1, arr_min2))

arr = [1000, 11, 445, 1, 330, 3000]

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

Maximum element is 3000

Result
EX NO :
Merge Sort
DATE:

Aim

Algorithm
Program
def merge_sort(arr):

if len(arr) <= 1:

return arr

# Split the array in half

mid = len(arr) // 2

left = arr[:mid]

right = arr[mid:]

# Recursively sort the left and right halves

left = merge_sort(left)

right = merge_sort(right)

# Merge the sorted left and right halves

result = []

i=0

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.extend(left[i:])

result.extend(right[j:])

return result

a=[20,12,34,10,52,19]

print(“The sorted array using merge sort: “,merge_sort(a));

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 = []

for element in arr:

if element < pivot:

less.append(element)

elif element > pivot:

greater.append(element)

else:

equal.append(element)

sorted_less = quick_sort(less)

sorted_greater = quick_sort(greater)

return sorted_less + equal + sorted_greater

a=[20,12,34,10,52,19]

print(“The sorted array using Quick sort: “,quick_sort(a))


Output
The sorted array using Quick sort: 10,12,19,20,34,52

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

print()

def isSafe(board, row, col):

for i in range(col):

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

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

def kthSmallest(arr, l, r, k):

if (k > 0 and k <= r - l + 1):

pos = randomPartition(arr, l, r)

if (pos - l == k - 1):

return arr[pos]

if (pos - l > k - 1):

return kthSmallest(arr, l, pos - 1, k)

return kthSmallest(arr, pos + 1, r,k - pos + l - 1)

return 999999999999

def swap(arr, a, b):

temp = arr[a]

arr[a] = arr[b]

arr[b] = temp

def partition(arr, l, r):

x = arr[r]

i=l

for j in range(l, r):

if (arr[j] <= x):

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

if name == ' main ':

arr = [12, 3, 5, 7, 4, 19, 26]

n = len(arr)

k=3

print("K'th smallest element is", kthSmallest(arr, 0, n - 1, k));

Output
K'th smallest element is 5

Result

You might also like