Algorithm Lab Manual Updated 1
Algorithm Lab Manual Updated 1
Ex. Date of
Date Name of the Pg. Marks Sign Remarks
No completion
Exercise No.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
DATE:
AIM:
ALGORITHM:
Program:
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
if(res == -1):
Downloaded by Saravanan Sujatha (ssujatha8476@gmail.com)
lOMoARcPSD|28042479
else:
Output:
RESULT:
DATE:
AIM:
ALGORITHM:
Program:
low = 0
high = len(list1) - 1
mid = 0
if list1[mid] < n:
low = mid + 1
high = mid - 1
else:
return mid
return -1
# Initial list1
n = 45
# Function call
result = binary_search(list1, n)
if result != -1:
else:
Output:
RESULT:
Thus the program using Recursive binary search algorithms was executed successfully.
AIM:
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:
#include<string.h>
int main() {
int position;
gets(a);
gets(b);
if (position != -1) {
else {
printf("Not found.\n");
return 0;
text_length = strlen(text);
pattern_length = strlen(pattern);
return -1;
position = e = c;
if (pattern[d] == text[e]) {
e++;
else {
break;
}}
if (d == pattern_length) {
return position;
} }return -1;
Output:
RESULT:
Thus the program using pattern matching algorithms was executed successfully
DATE:
AIM:
To implement insertion sort and heap sort. 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:
PROGRAM:
Insertion sort:
def InsertionSort(a):
temp = a[i]
j = i-1
Downloaded by Saravanan Sujatha (ssujatha8476@gmail.com)
lOMoARcPSD|28042479
a[j+1] = a[j]
j -= 1
a[j+1] = temp
# array to be sorted
a = [10, 5, 13, 8, 2]
InsertionSort(a)
print(a)
Heap sort:
def heapify(array, a, b):
largest = b
l=2*b+
root = 2 * b + 2
largest = l
largest = root
# Change root
if largest != b:
heapify(array, a, largest)
def Heap_Sort(array):
a = len(array)
# maxheap..
heapify(array, a, b)
# extract elements
heapify(array, b, 0)
# Driver code
array = [ 7, 2, 5, 6, 3, 1, 8, 4]
Heap_Sort(array)
a = len(array)
OUTPUT:
Insertion sort:
Heap sort:
RESULT:
Thus the program using Insertion sort and heap sort algorithms was executed
successfully.
Graph Algorithms
DATE:
AIM:
ALGORITHM:
#include<stdio.h>
int queue[100];
int front=0,back=0;
queue[back] = var;
back++;
void pop()
queue[front] = 0;
front++;
int main()
int N = 6;
{1,0,1,0,0,0},
{1,1,0,1,1,0},
{0,0,1,0,0,0},
{0,0,1,0,0,1},
{0,0,0,0,1,0}};
push(1);
while(front != back)
pop();
for(int i=0;i<6;i++)
push(i+1);
return 0;
OUTPUT:
123456
RESULT:
Thus the program using Breadth first search algorithms was executed successfully.
DATE:
AIM:
ALGORITHM:
Program:
# DFS algorithm
if visited is None:
visited = set()
visited.add(start)
print(start)
return visited
'2': set(['0']),
'3': set(['1']),
dfs(graph, '0')
Output
RESULT:
Thus the program using Depth first search algorithms was executed successfully.
DATE:
AIM:
ALGORITHM:
Program:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 9
return min_index;
// array
// shortest
// included in shortest
// finalized
// false
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 9
return min_index;
// array
// shortest
// included in shortest
// finalized
// false
dist[src] = 0;
sptSet[u] = true;
// picked vertex.
printSolution(dist);
// driver's code
int main()
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
// Function call
dijkstra(graph, 0);
return 0;
Output :
RESULT:
AIM:
To find the minimum cost spanning tree of a given undirected graph using
prim’s algorithm.
ALGORITHM:
Program:
selected_node = [0, 0, 0, 0, 0]
no_edge = 0
selected_node[0] = True
minimum = INF
a=0
b=0
for m in range(N):
if selected_node[m]:
Downloaded by Saravanan Sujatha (ssujatha8476@gmail.com)
lOMoARcPSD|28042479
for n in range(N):
if ((not selected_node[n]) and G[m][n]):
# not in selected and there is an edge
if minimum > G[m][n]:
minimum = G[m][n]
a=m
b=n
print(str(a) + "-" + str(b) + ":" + str(G[a][b]))
selected_node[b] = True
no_edge += 1
Output:
RESULT:
DATE:
AIM:
To implement Floyd’s algorithm for the all pairs shortest paths problem.
ALGORITHM:
PROGRAM:
nV = 4
INF = 999
# Algorithm implementation
def floyd_warshall(G):
for k in range(nV):
for i in range(nV):
for j in range(nV):
print_solution(distance)
def print_solution(distance):
for i in range(nV):
for j in range(nV):
if(distance[i][j] == INF):
else:
print(" ")
[INF, 1, 0, INF],
floyd_warshall(G)
OUTPUT
RESULT:
DATE:
AIM:
ALGORITHM:
PROGRAM:
#Complexity : O(V^3)
class Graph:
self.V = vertices
for i in range(self.V):
for j in range(self.V):
if (i == j):
else:
print()
def transitiveClosure(self,graph):
vertices.
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
self.printSolution(reach)
g= Graph(4)
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]]
g.transitiveClosure(graph)
OUTPUT:
RESULT:
AIM:
ALGORITHM:
Program:
#include <iostream>
#include <vector>
#include <climits>
// Divide and conquer solution to find the minimum and maximum number in an array
void findMinAndMax(vector<int> const &nums, int low, int high, int &min, int &max)
max = nums[low];
min = nums[high];
} return; }
min = nums[low];
max = nums[high]; }
else {
min = nums[high];
max = nums[low];
return;
int main()
vector<int> nums = { 7, 2, 9, 3, 1, 6, 7, 8, 4 };
int n = nums.size();
cout << "The minimum array element is " << min << endl;
cout << "The maximum array element is " << max << endl;
return 0;
RESULT:
Thus the program using divide and conquer algorithms was executed successfully.
AIM:
ALGORITHM:
6. To included solve the problems (merge sort and quick sort algorithms).
Program:
# This implementation utilizes pivot as the last element in the nums list
# It has a pointer to keep track of the elements smaller than the pivot
# At the very end of partition() function, the pointer is swapped with the pivot
pivot = array[high]
i = low - 1
i=i+1
return i + 1
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print(data)
Output
Merge Sort
Program:
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
L[i] = arr[l + i]
R[j] = arr[m + 1 + j]
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# are any
arr[k] = L[i]
i += 1
k += 1
# are any
Downloaded by Saravanan Sujatha (ssujatha8476@gmail.com)
lOMoARcPSD|28042479
arr[k] = R[j]
j += 1
k += 1
if l < r:
# large l and h
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
n = len(arr)
for i in range(n):
Downloaded by Saravanan Sujatha (ssujatha8476@gmail.com)
lOMoARcPSD|28042479
mergeSort(arr, 0, n-1)
for i in range(n):
Output
RESULT:
Thus the program using merge sort and quick sort algorithms was executed successfully.
AIM:
ALGORITHM:
Program:
# Python program to solve N Queen
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print()
# attacking queens
for i in range(col):
if board[row][i] == 1:
return False
if board[i][j] == 1:
return False
if board[i][j] == 1:
return False
return True
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
return True
board[i][col] = 0
return False
# feasible solutions.
def solveNQ():
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
if solveNQUtil(board, 0) == False:
return False
printSolution(board)
return True
solveNQ()
Output:
RESULT:
DATE:
AIM:
To implement any scheme to find the optimal solution for the traveling
salesman problem and then solve the same problem instance using approximation
algorithm and determine the error in the approximation.
ALGORITHM:
PROGRAM:
#include <stdio.h>
int tsp(int c)
temp = matrix[c][count];
nearest_city = count;
if(minimum != 999)
return nearest_city;
int nearest_city;
visited_cities[city] = 1;
nearest_city = tsp(city);
if(nearest_city == 999)
nearest_city = 0;
return;
minimum_cost(nearest_city);
int main()
int i, j;
scanf("%d", &limit);
scanf("%d", &matrix[i][j]);
visited_cities[i] = 0;
printf("\n");
printf("\n\nPath:\t");
minimum_cost(0);
printf("%d\n", cost);
return 0;
RESULT:
DATE:
AIM:
ALGORITHM:
PROGRAM:
lst.sort()
return lst[k-1]
nums = [1,2,4,3,5,4,6,9,2,1]
print("Original list:")
print(nums)
k=1
print(kth_smallest_el(nums, k))
k=k+1
Output:
RESULT: