lOMoARcPSD|23829454
Algorithm Lab Manual updated 1
Design and Analysis of Algorithms (Anna University)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Bharathi V (
[email protected])
lOMoARcPSD|23829454
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.
lOMoARcPSD|23829454
Searching and Sorting Algorithms
lOMoARcPSD|23829454
Ex.No:1 LINEAR SEARCH
DATE:
AIM:
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:
1. Start the program.
2. To create linear search algorithm.
3. Searching the values and solve the problems.
4. To create binary values.
5. To list to be searched and plot a graph.
6. To included solve the problems (Linear Search).
7. Stop the program.
Program:
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
Downloaded by Bharathi V ([email protected])
lOMoARcPSD|23829454
print("Element not found")
else:
print("Element found at index: ", res)
Output:
Element found at index: 4
RESULT:
Thus the program using linear search algorithms was executed
successfully.
lOMoARcPSD|23829454
EX.NO:2 RECURSIVE BINARY SEARCH
DATE:
AIM:
To Implement Recursive Binary 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:
1. Start the program.
2. To create Recursive Binary search algorithm.
3. Searching the values and solve the problems.
4. To create binary values.
5. To list to be searched and plot a graph.
6. To included solve the problems (Recursive Binary Search).
7. Stop the program.
Program:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
# for get integer result
mid = (high + low) // 2
# Check if n is present at mid
if list1[mid] < n:
low = mid + 1
lOMoARcPSD|23829454
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1
# If n is smaller, compared to the left of mid
else:
return mid
# element was not present in the list, return -1
return -1
# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
# Function call
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
Output:
Element in present at index 2
lOMoARcPSD|23829454
RESULT:
Thus the program using Recursive binary search algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:3 PATTERN MACHING
DATE:
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:
1. Start the program.
2. To given text tx[0….n-1].
3. Pattern pat[0…m-1] and solve the problems.
4. To assume n > m values.
5. To print all occurrences of pat[] in txt[].
6. To included solve the problems.
7. Stop the program
PROGRAM:
#include <stdio.h>
#include<string.h>
int match(char [], char []);
int main() {
char a[100], b[100];
int position;
printf("Enter some text\n");
gets(a);
printf("Enter a string to find\n");
gets(b);
position = match(a, b);
if (position != -1) {
printf("Found at location: %d\n", position + 1);
else {
printf("Not found.\n");
return 0;
lOMoARcPSD|23829454
int match(char text[], char pattern[]) {
int c, d, e, text_length, pattern_length, position = -1;
text_length = strlen(text);
pattern_length = strlen(pattern);
if (pattern_length > text_length) {
return -1;
for (c = 0; c <= text_length - pattern_length; c++) {
position = e = c;
for (d = 0; d < pattern_length; d++) {
if (pattern[d] == text[e]) {
e++;
else {
break;
}}
if (d == pattern_length) {
return position;
} }return -1;
Output:
lOMoARcPSD|23829454
lOMoARcPSD|23829454
RESULT:
Thus the program using pattern matching algorithms was executed successfully
lOMoARcPSD|23829454
EX.NO:4 INSERTIONS AND HEAP SORT
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:
1. Start the program.
2. To create insertion sort and heap sort algorithm.
3. Searching the values and solve the problems.
4. To create binary values.
5. To list to be sorted and plot a graph.
6. To included solve the problems (insertion sort, heap sort).
7. Stop the program.
PROGRAM:
Insertion sort:
def InsertionSort(a):
# traversing the array from 1 to length of the array(a)
for i in range(1, len(a)):
temp = a[i]
# Shift elements of array[0 to i-1], that are
# greater than temp, to one position ahead
# of their current position
j = i-1
Downloaded by Bharathi V ([email protected])
lOMoARcPSD|23829454
while j >=0 and temp < a[j] :
a[j+1] = a[j]
j -= 1
a[j+1] = temp
# array to be sorted
a = [10, 5, 13, 8, 2]
InsertionSort(a)
print("Array after sorting:")
print(a)
Heap sort:
def heapify(array, a, b):
largest = b
l=2*b+
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):
lOMoARcPSD|23829454
a = len(array)
lOMoARcPSD|23829454
# 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: ", array)
Heap_Sort(array)
a = len(array)
print ("Array after sorting is: ", array)
OUTPUT:
Insertion sort:
lOMoARcPSD|23829454
Heap sort:
RESULT:
Thus the program using Insertion sort and heap sort algorithms was executed
successfully.
lOMoARcPSD|23829454
Graph Algorithms
lOMoARcPSD|23829454
EX.NO:5 BREADTH FIRST SEARCHES
DATE:
AIM:
To implement graph traversal using Breadth first Search.
ALGORITHM:
1. Start the program.
2. To create Breadth first search algorithm.
3. Searching the values and solve the problems.
4. To create binary values.
5. To list to be searched and plot a graph.
6. To included solve the problems (Breadth first Search).
7. Stop the program.
PROGRAM:
#include<stdio.h>
// creating queue data structure using arrays
int queue[100];
// defining pointers of the queue to perform pop and push
int front=0,back=0;
// defining push operation on the queue
void push(int var)
queue[back] = var;
back++;
lOMoARcPSD|23829454
// defining pop operation on queue
void pop()
queue[front] = 0;
front++;
// creating a visited array to keep the track of visited nodes
int visited[7] = {0};
int main()
// defining the number of total persons
int N = 6;
// adjacenty matrix representing graph
int graph[6][6] = {{0,1,1,0,0,0},
{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}};
// front == back stands for empty queue
// until queue is not empty perfromingbfs
// adding a starting node in the list
lOMoARcPSD|23829454
push(1);
visited[0] = 1; // marking 1st node as visited
while(front != back)
int current = queue[front];
// printing current element
printf("%d ", current);
// popping the front element from the queue
pop();
for(int i=0;i<6;i++)
// adding non-visited connected nodes of the current node to the queue
if((graph[current-1][i] == 1) && (visited[i] == 0))
visited[i] = 1; // marking visisted
push(i+1);
return 0;
OUTPUT:
123456
lOMoARcPSD|23829454
RESULT:
Thus the program using Breadth first search algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:6 DEPTH FIRST SEARCH
DATE:
AIM:
To implement graph traversal using Depth first Search.
ALGORITHM:
1. Start the program.
2. To create Depth first search algorithm.
3. Searching the values and solve the problems.
4. To create binary values.
5. To list to be searched and plot a graph.
6. To included solve the problems (Depth first Search).
7. Stop the program.
Program:
# DFS algorithm in Python
# DFS algorithm
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
lOMoARcPSD|23829454
graph = {'0': set(['1', '2']),
'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}
dfs(graph, '0')
Output
RESULT:
Thus the program using Depth first search algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:7 DIJIKSTRA ALGORITHMS
DATE:
AIM:
To given vertex in a weighted connected graph, develop a program to find
the shortest paths to other vertices using Dijkstra’s algorithm.
ALGORITHM:
1. Start the program.
2. To create Dijkstra’s algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (Dijkstra’s algorithms).
7. Stop the program
Program:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
// Initialize min value
int min = INT_MAX, min_index;
lOMoARcPSD|23829454
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
// A utility function to print the constructed distance
// array
void printSolution(int dist[])
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is
// included in shortest
lOMoARcPSD|23829454
// path tree or shortest distance from src to i is
// finalized
// Initialize all distances as INFINITE and stpSet[] as
// false
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 9
// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
// A utility function to print the constructed distance
// array
void printSolution(int dist[])
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
lOMoARcPSD|23829454
// Function that implements Dijkstra's single source
// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is
// included in shortest
// path tree or shortest distance from src to i is
// finalized
// Initialize all distances as INFINITE and stpSet[] as
// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed. u is always equal to
// src in the first iteration.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int v = 0; v < V; v++)
// Update dist[v] only if is not in sptSet,
// there is an edge from u to v, and total
lOMoARcPSD|23829454
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
// print the constructed distance array
printSolution(dist);
// driver's code
int main()
/* Let us create the example graph discussed above */
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;
lOMoARcPSD|23829454
Output :
RESULT:
Thus the program using Dijkstra’s algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:8 Prim’s algorithm.
DATE:
AIM:
To find the minimum cost spanning tree of a given undirected graph using
prim’s algorithm.
ALGORITHM:
1. Start the program.
2. To create prim’s algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (prim’s algorithms).
7. Stop the program
Program:
# Prim's Algorithm in Python
INF = 9999999
# number of vertices in graph
N=5
#creating graph by adjacency matrix method
G = [[0, 19, 5, 0, 0],
[19, 0, 5, 9, 2],
[5, 5, 0, 1, 6],
[0, 9, 1, 0, 1],
[0, 2, 6, 1, 0]]
selected_node = [0, 0, 0, 0, 0]
no_edge = 0
selected_node[0] = True
# printing for edge and weight
print("Edge : Weight\n")
while (no_edge < N - 1):
minimum = INF
a=0
b=0
for m in range(N):
if selected_node[m]:
Downloaded by Bharathi V ([email protected])
lOMoARcPSD|23829454
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:
Thus the program using prim’s algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:9 FLOYD'S ALGORITHM
DATE:
AIM:
To implement Floyd’s algorithm for the all pairs shortest paths problem.
ALGORITHM:
1. Start the program.
2. To create Floyd’s algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (Floyd’s algorithms).
7. Stop the program
PROGRAM:
# Floyd Warshall Algorithm in python
# The number of vertices
nV = 4
INF = 999
# Algorithm implementation
def floyd_warshall(G):
distance = list(map(lambda i: list(map(lambda j: j, i)), G))
# Adding vertices individually
lOMoARcPSD|23829454
for k in range(nV):
for i in range(nV):
for j in range(nV):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
print_solution(distance)
# Printing the solution
def print_solution(distance):
for i in range(nV):
for j in range(nV):
if(distance[i][j] == INF):
print("INF", end=" ")
else:
print(distance[i][j], end=" ")
print(" ")
G = [[0, 3, INF, 5],
[2, 0, INF, 4],
[INF, 1, 0, INF],
[INF, INF, 2, 0]]
floyd_warshall(G)
lOMoARcPSD|23829454
OUTPUT
RESULT:
Thus the program using Floyd’s algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:10 WARSHALL’S ALGORITHM
DATE:
AIM:
To compute the transitive closure of a given directed graph using Warshall’s
algorithm.
ALGORITHM:
1. Start the program.
2. To create Warshall’s algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (Warshall’s algorithms).
7. Stop the program
PROGRAM:
# Python program for transitive closure using Floyd Warshall Algorithm
#Complexity : O(V^3)
from collections import defaultdict
#Class to represent a graph
class Graph:
def init (self, vertices):
self.V = vertices
# A utility function to print the solution
def printSolution(self, reach):
lOMoARcPSD|23829454
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()
# Prints transitive closure of graph[][] using Floyd Warshall algorithm
def transitiveClosure(self,graph):
'''reach[][] will be the output matrix that will finally
have reachability values.
Initialize the solution matrix same as input graph matrix'''
reach =[i[:] for i in graph]
'''Add all vertices one by one to the set of intermediate
vertices.
---> Before start of a iteration, we have reachability value
for all pairs of vertices such that the reachability values
consider only the vertices in set
{0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of an iteration, vertex no. k is
added to the set of intermediate vertices and the
set becomes {0, 1, 2, .. k}'''
for k in range(self.V):
# Pick all vertices as source one by one
lOMoARcPSD|23829454
for i in range(self.V):
# Pick all vertices as destination for the
# above picked source
for j in range(self.V):
# If vertex k is on a path from i to j,
# then make sure that the value of reach[i][j] is 1 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]]
#Print the solution
g.transitiveClosure(graph)
#This code is contributed by Neelam Yadav
lOMoARcPSD|23829454
OUTPUT:
RESULT:
Thus the program using Warshell’s algorithms was executed successfully.
lOMoARcPSD|23829454
Algorithm Design Techniques
lOMoARcPSD|23829454
EX.NO:11 DIVIDE AND CONQUER TECHNIQUE
DATE:
AIM:
To develop a program to find out the maximum and minimum numbers in a
given list of n numbers using the divide and conquer.
ALGORITHM:
1. Start the program.
2. To create divide and conquer algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (divide and conquer algorithms).
7. Stop the program
Program:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// 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)
// if the array contains only one element
if (low == high) // common comparison
if (max < nums[low]) { // comparison 1
max = nums[low];
if (min > nums[high]) { // comparison 2
min = nums[high];
lOMoARcPSD|23829454
} return; }
// if the array contains only two elements
if (high - low == 1) // common comparison
if (nums[low] < nums[high]) // comparison 1
if (min > nums[low]) { // comparison 2
min = nums[low];
if (max < nums[high]) { // comparison 3
max = nums[high]; }
else {
if (min > nums[high]) { // comparison 2
min = nums[high];
if (max < nums[low]) { // comparison 3
max = nums[low];
return;
// find the middle element
int mid = (low + high) / 2;
// recur for the left subarray
findMinAndMax(nums, low, mid, min, max);
// recur for the right subarray
findMinAndMax(nums, mid + 1, high, min, max);
int main()
lOMoARcPSD|23829454
vector<int> nums = { 7, 2, 9, 3, 1, 6, 7, 8, 4 };
// initialize the minimum element by INFINITY and the
// maximum element by -INFINITY
int max = INT_MIN, min = INT_MAX;
int n = nums.size();
findMinAndMax(nums, 0, n - 1, min, max);
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.
lOMoARcPSD|23829454
EX.NO:12 MERGE SORT AND QUICK SORT
DATE:
AIM:
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:
1. Start the program.
2. To create merge sort and Quick sort algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (merge sort and quick sort algorithms).
7. Stop the program
Program:
# Python program for implementation of Quicksort Sort
# 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
# to come up with a "sorted" nums relative to the pivot
# Function to find the partition position
def partition(array, low, high):
lOMoARcPSD|23829454
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# If element smaller than pivot is found
# swap it with the greater element pointed by i
i=i+1
# Swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
# Swap the pivot element with the greater element specified by i
(array[i + 1], array[high]) = (array[high], array[i + 1])
# Return the position from where partition is done
return i + 1
# function to perform quicksort
lOMoARcPSD|23829454
def quickSort(array, low, high):
if low < high:
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)
# Recursive call on the left of pivot
quickSort(array, low, pi - 1)
# Recursive call on the right of pivot
quickSort(array, pi + 1, high)
data = [1, 7, 4, 1, 10, 9, -2]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
lOMoARcPSD|23829454
Output
Merge Sort
Program:
# Python program for implementation of MergeSort
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0, n1):
L[i] = arr[l + i]
lOMoARcPSD|23829454
for j in range(0, n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i=0 # Initial index of first subarray
j=0 # Initial index of second subarray
k=l # Initial index of merged subarray
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
Downloaded by Bharathi V ([email protected])
lOMoARcPSD|23829454
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr, l, r):
if l < r:
# Same as (l+r)//2, but avoids overflow for
# large l and h
m = l+(r-l)//2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
Downloaded by Bharathi V ([email protected])
lOMoARcPSD|23829454
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")
# This code is contributed by Mohit Kumra
Output
RESULT:
Thus the program using merge sort and quick sort algorithms was executed successfully.
lOMoARcPSD|23829454
Space Search Algorithms
lOMoARcPSD|23829454
EX.NO:13 N QUEENS PROBLEM
DATE:
AIM:
To implement N Queens problem using backtracking.
ALGORITHM:
1. Start the program.
2. To create backtracking algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (backtracking algorithms).
7. Stop the program
Program:
# Python program to solve N Queen
# Problem using backtracking
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
# A utility function to check if a queen can
Downloaded by Bharathi V (
[email protected])
lOMoARcPSD|23829454
# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
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):
# base case: If all queens are placed
# then return true
if col >= N:
lOMoARcPSD|23829454
return True
# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0
# if the queen can not be placed in any row in
# this column col then return false
return False
# This function solves the N Queen problem using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
lOMoARcPSD|23829454
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
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 program to test above function
solveNQ()
# This code is contributed by Divyanshu Mehta
Output:
lOMoARcPSD|23829454
RESULT:
Thus the program using backtracking algorithms was executed successfully.
lOMoARcPSD|23829454
Approximation Algorithms Randomized Algorithms
lOMoARcPSD|23829454
EX.NO:14 TRAVELLING SALES PERSON PROBLEM
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:
1. Start the program.
2. To create approximation algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (approximation algorithm)
7. Stop the program
PROGRAM:
#include <stdio.h>
int matrix[25][25], visited_cities[10], limit, cost = 0;
int tsp(int c)
int count, nearest_city = 999;
int minimum = 999, temp;
for(count = 0; count < limit; count++)
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
if(matrix[c][count] < minimum)
lOMoARcPSD|23829454
minimum = matrix[count][0] + matrix[c][count];
temp = matrix[c][count];
nearest_city = count;
if(minimum != 999)
cost = cost + temp;
return nearest_city;
void minimum_cost(int city)
int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if(nearest_city == 999)
nearest_city = 0;
printf("%d", nearest_city + 1);
cost = cost + matrix[city][nearest_city];
return;
minimum_cost(nearest_city);
lOMoARcPSD|23829454
int main()
int i, j;
printf("Enter Total Number of Cities:\t");
scanf("%d", &limit);
printf("\nEnter Cost Matrix\n");
for(i = 0; i< limit; i++)
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
scanf("%d", &matrix[i][j]);
visited_cities[i] = 0;
printf("\nEntered Cost Matrix\n");
for(i = 0; i< limit; i++)
printf("\n");
for(j = 0; j < limit; j++)
printf("%d ", matrix[i][j]);
printf("\n\nPath:\t");
minimum_cost(0);
printf("\n\nMinimum Cost: \t");
lOMoARcPSD|23829454
printf("%d\n", cost);
return 0;
lOMoARcPSD|23829454
RESULT:
Thus the program using approximation algorithms was executed successfully.
lOMoARcPSD|23829454
EX.NO:15 Randomized algorithms for finding the kth smallest number
DATE:
AIM:
To implement randomized algorithms for finding them kth smallest number
.
ALGORITHM:
1. Start the program.
2. To create randomized algorithm.
3. Sorting the values and solve the problems.
4. To create binary values.
5. To list to be sorted in graph.
6. To included solve the problems (randomized algorithm)
7. Stop the program
PROGRAM:
#code for k smallest elements in an array
def kth_smallest_el(lst, k):
lst.sort()
return lst[k-1]
nums = [1,2,4,3,5,4,6,9,2,1]
print("Original list:")
print(nums)
k=1
for i in range(1, 11):
print("kth smallest element in the said list, when k = ",k)
print(kth_smallest_el(nums, k))
k=k+1
lOMoARcPSD|23829454
Output:
RESULT:
Thus the program using approximation algorithms was executed successfully.