23CST404 Algorithms Lab NUMBERED
23CST404 Algorithms Lab NUMBERED
ENGINEERING COLLEGE
(An Autonomous Institution)
KARUDAYAMPALAYAM, KARUR – 639 111.
Name :
Reg. No. :
Subject :
Semester :
1
V.S.B. ENGINEERING COLLEGE
(An Autonomous Institution)
KARUDAYAMPALAYAM, KARUR – 639 111.
RECORD
NAME: CLASS:
REGISTER NO.
ROLL NO.
held on ……………………………….
2
CONTENTS
Page Marks
Sl.No. Date Name of Experiment Sign.
No. Award
3
CONTENTS
Page Marks
Sl.No. Date Name of Experiment Sign.
No. Award
4
CO,PO,PSO MAPPING
CO PO PSO
S.No Name of the Experiment Mapping
Mapping Mapping
1 Implement Linear Search. Determine the time required to CO1
search for an element. Repeat the experiment for different 1,2,3,4,9,
1,2,3
values of n, the number of elements in the list to 10,11,12
be searched and plot a graph of the time taken versus n.
2 Implement recursive Binary Search. Determine the time CO1
required to search an element. Repeat the experiment for 1,2,3,4,9,
different values of n, the number of elements in the list to 1,2,3
be searched and plot a graph of the time taken versus n. 10,11,12
3 Given a text txt [0...n-1] and a pattern pat [0...m-1], write a CO1
function search (char pat [ ], char txt [ ]) that prints all 1,2,3,4,9,
occurrences of pat [ ] in txt [ ]. You may assume that n > 1,2,3
10,11,12
m.
4 Sort a given set of elements using the Insertion sort and CO1
Heap sort methods and determine the time required to sort
1,2,3,4,9,
the elements. Repeat the experiment for different values of 1,2,3
n, the number of elements in the list to be 10,11,12
sorted and plot a graph of the time taken versus n.
5 Develop a program to implement graph traversal using CO2 1,2,3,4,5,9,
Breadth First Search 10,11,12 1,2,3
6 Develop a program to implement graph traversal using CO2 1,2,3,4,5,9,
Depth First Search 10,11,12 1,2,3
7 From a given vertex in a weighted connected graph,
CO2 1,2,3,4,5,9,
develop a program to find the shortest paths to other 1,2,3
10,11,12
vertices using Dijkstra’s algorithm.
8 Find the minimum cost spanning tree of a given undirected 1,2,3,4,5,9,
CO2 1,2,3
graph using Prim’s algorithm. 10,11,12
9 Implement Floyd’s algorithm for the All-Pairs- Shortest- CO2 1,2,3,4,5,9,
Paths problem. 10,11,12 1,2,3
10 Compute the transitive closure of a given directed graph 1,2,3,4,5,9,
using Warshall's algorithm. CO2 1,2,3
10,11,12
11 Develop a program to find out the maximum and
CO3 1,2,3,4,5,9,
minimum numbers in a given list of n numbers using the 1,2,3
divide and conquer technique. 10,11,12
12 Implement Merge sort and Quick sort methods to sort an
array of elements and determine the time required to sort. CO3
1,2,3,4,5,9,
Repeat the experiment for different values of n, the 1,2,3
number of elements in the list to be sorted and plot a graph 10,11,12
of the time taken versus n.
13 Implement N Queens problem using Backtracking. 1,2,3,4,9,
CO4 1,2,3
10,11,12
14 Implement any scheme to find the optimal solution for the
Traveling Salesperson problem and then solve the same CO5 1,2,3,4,5,9,
problem instance using any approximation algorithm and 1,2,3
10,11,12
determine the error in the approximation.
15 Implement randomized algorithms for finding the kth 1,2,3,4,5,9,
smallest number. CO5 1,2,3
10,11,12
5
V.S.B. Engineering College, Karur
We endeavour to impart futuristic technical education of the highest quality to the student
community and to inculcate discipline in them to face the world with self-confidence and thus we
prepare them for life as responsible citizens to uphold human values and to be of service at large.
We strive to bring of the Institution as an Institution of academic excellence of International
standard.
We transform persons into personalities by the state-of the art infrastructure, time consciousness,
quick response and the best academic practices through assessment and advice.
The Department strives to contribute to the expansion of knowledge in the discipline of Computer
Science and Engineering by,
• adopting an efficient teaching learning process in correlation with industrial needs.
• ensuring technical proficiency, facilitating to pursue higher studies and carry out
R&D activities.
• developing problem solving and analytical skills with sound knowledge in basic
sciences and Computer Science Engineering.
• inculcating managerial skills to become socially responsible, ethical and competitive
professionals.
6
Programme Educational Objectives (PEOs)
7
PO7: Environment and sustainability
Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
.PO8: Ethics
Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work
Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
PO10: Communication
Communicate effectively on complex engineering activities with the engineering community
and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance
Demonstrate knowledge and understanding of the engineering and management principles
and apply these to one’s own work, as a member and leader in a team, to manage projects
and in multidisciplinary environments.
PO12: Life-long learning
Recognize the need for, and have the preparation and ability to engage in independent and
life-long learning in the broadest context of technological change.
PSO1: Addressing societal problems through design and development of software and
firmware solutions using latest Computer Science tools and technologies.
PSO3: Use their technical expertise in latest technologies and update their knowledge
continuously in Computer Science and Engineering to excel in their career.
8
COURSE OBJECTIVES:
• To understand and apply the algorithm analysis techniques on searching
and sorting algorithms
• To critically analyze the efficiency of graph algorithms
• To understand different algorithm design techniques
• To solve programming problems using state space tree
• To understand the concepts behind NP Completeness, Approximation
algorithms and randomized algorithms.
COURSE OUTCOMES:
At the end of this course, the students will be able to:
CO1: Analyze the efficiency of algorithms using various frameworks
CO2: Apply graph algorithms to solve problems and analyze their efficiency.
CO3: Make use of algorithm design techniques like divide and conquer,
dynamic programming and greedy techniques to solve problems
CO4: Use the state space tree method for solving problems.
CO5: Solve problems using approximation algorithms and randomized algorithms
9
SYLLABUS
L T P C
ALGORITHMS
23CST404
3 0 2 4
Graph Algorithms
1. Develop a program to implement graph traversal using Breadth First Search
2. Develop a program to implement graph traversal using Depth First Search
3. From a given vertex in a weighted connected graph, develop a program to find the shortest
paths to other vertices using Dijkstra’s algorithm.
4. Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
5. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.
6. Compute the transitive closure of a given directed graph using Warshall's algorithm.
10
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 C program to implement Linear Search. Determine the time required to search
for an element.
ALGORITHM:
Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the array.
Step 3: If both are matched, display “Target element is found” and terminate the Linear Search
function.
Step 4: If both are not matched, compare the search element with the next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared with the
last element of the array.
Step 6 – If the last element in the list does not match, the Linear Search Function will be
terminated, and the message “Element is not found” will be displayed.
PROGRAM:
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);
return 0;
}
11
OUTPUT:
Enter the number of elements in array
5
Enter 5 integer(s)
12
34
02
05
18
Enter the number to search
02
2 is present at location 3.
Time Complexity Analysis Linear Search time complexity analysis is done below.
Best case time complexity = O(1).
Average Case time complexity = O(n)
Worst case time complexity = O(n).
Thus, we have Time Complexity of Linear Search Algorithm is O(n).
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
12
EX NO:2 Implement recursive Binary Search. Determine the time required to search 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 C program to implement recursive Binary Search Determine the time required to
search an element.
ALGORITHM:
Step 1 : Find the middle element of array. using ,
middle = initial_value + end_value / 2 ;
Step 2 : If middle = element, return ‘element found’ and index.
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.
PROGRAM:
#include <stdio.h>
int recursiveBinarySearch(int array[], int start_index, int end_index, int element){
if (end_index >= start_index){
int middle = start_index + (end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return recursiveBinarySearch(array, start_index, middle-1, element);
return recursiveBinarySearch(array, middle+1, end_index, element);
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 9;
int found_index = recursiveBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}
13
OUTPUT:
Element found at index : 3
Time Complexity
Worst case time complexity: O(log n)
Average case time complexity: O(log n)
Best case time complexity: O(1)
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
14
EX NO: 03 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 [ ].
Date: You may assume that n > m.
AIM:
To write a C program and to write a function search (char pat [ ], char txt [ ]) that prints all
occurrences of pat [ ] in txt [ ].
ALGORITHM:
Step 1: Start the program
Step 2: Initially calculate the hash value of the pattern..
Step 3: Start iterating from the starting of the string.
Step 4 Calculate the hash value of the current substring having length m..
Step 5: If they are same, store the starting index as a valid answer. Otherwise, continue for the next
substrings.
Step6: Return the starting indices as the required answer.
Step 7: Stop the program
PROGRAM:
#include <stdio.h>
#include <string.h>
void search(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;if (j == M)
printf("Pattern found at index %d \n", i);// if pat[0...M-1] //= txt[i, i+1, ...i+M-1]
}
}
int main(){
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search (pat,txt);
return 0;
}
15
OUTPUT:
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
16
Sort a given set of elements using the Insertion sort methods and determine
EX NO : 4(a)
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
Date:
the time taken versus n.
AIM :
To write a C program for Sort a given set of elements using the Insertion sort methods and
determine the time required to sort the elements.
ALGORITHM :
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the
next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
PROGRAM :
// C program for insertion sort
#include <math.h>
#include <stdio.h>
17
}
}
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
18
OUTPUT :
5 6 11 12 13
Time Complexity
Worst case time complexity: O(n^2)
Average case time complexity: O(n^2)
Best case time complexity: O(n)
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
19
Sort a given set of elements using the Heap sort methods and determine the
EX NO : 4(b)
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
Date:
taken versus n.
AIM:
To write a C program to Sort a given set of elements using the Heap sort methods and
determine the time required to sort the elements
ALGORITHM:
Step 1: Start the program
Step 2: Build a max heap from the input data.
Step 3: At this point, the maximum element is stored at the root of the heap. Replace it with the
last item of the heap followed by reducing the size of the heap by 1. Finally, heapify the root of
the tree.
Step 4: Repeat step 2 while the size of the heap is greater than 1.
Step 5: Stop the program
PROGRAM:
// Heap Sort in C
#include <stdio.h>
*a = *b;
*b = temp;
}
// left = 2*i + 1
int left = 2 * i + 1;
// right = 2*i + 2
int right = 2 * i + 2;
20
// If left child is larger than root
if (left < N && arr[left] > arr[largest])
largest = left;
largest = right;
swap(&arr[i], &arr[largest]);
heapify(arr, N, i);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Driver's code
21
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}
OUTPUT:
Sorted array is
5 6 7 11 12 13
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
22
EX NO : 5
Develop a program to implement graph traversal using Breadth First Search
Date:
AIM:
To write a C program to implement graph traversal using Breadth First Search
ALGORITHM:
Step 1: Start program
Step 2 Start by putting any one of the graph's vertices at the back of a 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 the ones which aren't in the visited list to
the back of the queue.
Step 5: Keep repeating steps 2 and 3 until the queue is empty.
Step 6:Stop the program.
PROGRAM:
// BFS algorithm in C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
struct node {
int vertex;
struct node* next;
};
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
23
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
24
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
25
return item;
}
if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}
26
OUTPUT:
Queue contains
0 Resetting queue Visited 0
Queue contains
2 1 Visited 2
Queue contains
1 4 Visited 1
Queue contains
4 3 Visited 4
Queue contains
3 Resetting queue Visited 3
The time complexity of the BFS algorithm is represented in the form of O(V + E), where V is the
number of nodes and E is the number of edges.
The space complexity of the algorithm is O(V).
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
27
EX NO : 6
Develop a program to implement graph traversal using Depth First Search
Date:
AIM:-
To write a ‘C ' program to implement graph traversal using Depth First
Search.
ALGORITHM:-
PROGRAM :-
#include <stdio.h>
#include <stdlib.h>
// This pointer will be used to point to the next vertex in the adjacency list
// NULL will denote that this vertex was the last connected vertex
// with the vertex associated with the adjacency list
struct node *pointerToNextVertex;
};
// A boolean flag will be maintained to know whether we have already visited the node or
not
int *visitedRecord;
28
// And it will contain all nodes connected to the 1st vertex of the graph
struct node **adjacencyLists;
};
// Now provide the pointer stored for the adjacency list of source node to the newNode
newNode->pointerToNextVertex = graph->adjacencyLists[source];
// And assign the new Node as the starting point of our adjacency list of the source node
// In this way we are adding the newNode at the starting of the adjacency list
// because traversing to the end and then inserting will be an overhead
graph->adjacencyLists[source] = newNode;
29
// Parameters: Number of Vertices
struct Graph *createGraph(int vertices)
{
// Declare iterator variable for loop purpose
int i;
// Create the total "vertices" adjacency lists, means the array of adjacency lists
// Because still if we don't have the connection with any particular vertex
// The empty adjacency list is necessary
graph->adjacencyLists = malloc(vertices * sizeof(struct node *));
// Create the array visitedRecord to store the information about which nodes have been
visited till now.
graph->visitedRecord = malloc(vertices * sizeof(int));
// Initialize the visited record with 0, because at the time of the creation of a graph
// None of the vertex is visited
// And initialize the all adjacencyLists with NULL, because we don't have any edges while
creating the graph
for (i = 0; i < vertices; i++)
{
graph->adjacencyLists[i] = NULL;
graph->visitedRecord[i] = 0;
}
graph->visitedRecord[vertexNumber] = 1;
printf("%d ", vertexNumber);
30
if (graph->visitedRecord[connectedVertex] == 0)
{
depthFirstSearch(graph, connectedVertex);
}
temp = temp->pointerToNextVertex;
}
}
int main()
{
int numberOfVertices, numberOfEdges, i;
int source, destination;
int startingVertex;
31
OUTPUT :
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
32
EX NO : 7
From a given vertex in a weighted connected graph, develop a program to
find the shortest paths to other vertices using Dijkstra’s algorithm
Date:
AIM:-
To write a ‘C ' program to find the shortest paths to other vertices using Dijkstra’s
algorithm.
ALGORITHM:-
b. For each neighbor of the current node, calculate the distance to the neighbor through
the current node.
c. If the calculated distance is less than the previously recorded distance to the
neighbor, update the distance to the neighbor.
d. Mark the current node as visited and remove it from the set of unvisited nodes.
PROGRAM :-
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
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;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
33
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; 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];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}
34
OUTPUT :
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
35
EX NO : 8
Find the minimum cost spanning tree of a given undirected graph using
Prim’s algorithm
Date:
AIM:-
To write a C program for implementing the minimum cost spanning tree of a given
undirected graph using Prim’s algorithm.
ALGORITHM:-
PROGRAM :-
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
return min_index;
}
36
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
}
37
parent[v] = u, key[v] = graph[u][v];
}
// Driver's code
int main()
{
int graph[V][V] = { { 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 } };
return 0;
}
OUTPUT :
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
38
EX NO : 09
Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.
Date:
AIM:-
To write a ‘C ' program for implementing the Floyd’s algorithm for the All-
Pairs- Shortest-Paths problem
ALGORITHM:-
PROGRAM :-
// C Program for Floyd Warshall Algorithm
#include <stdio.h>
// Number of vertices in the graph
#define V 4
/* Define Infinite as a large enough
value. This value will be used
for vertices not connected to each other */
#define INF 99999
// A function to print the solution matrix
void printSolution(int dist[][V]);
39
have shortest distances between all
pairs of vertices such that the shortest
distances 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 = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of
// dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// driver's code
int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
40
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
// Function call
floydWarshall(graph);
return 0;
}
OUTPUT :
The following matrix shows the shortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 017
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
41
EX NO : 10
Compute the transitive closure of a given directed graph using Warshall's
algorithm
Date:
AIM:-
To write a ‘C ' program to Compute the transitive closure of a given directed
graph using Warshall's algorithm
ALGORITHM:-
PROGRAM :-
#include<stdio.h>
#include<conio.h>
#include<math.h>
int max(int, int);
void warshal(int p[10][10], int n) {
int i, j, k;
for (k = 1; k <= n; k++)
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
}
int max(int a, int b) {
;
if (a > b)
return (a);
else
return (b);
}
void main() {
int p[10][10] = { 0 }, n, e, u, v, i, j;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
42
printf("\n Enter the number of edges:");
scanf("%d", &e);
for (i = 1; i <= e; i++) {
//printf("\n Enter the end vertices of edge %d:", i);
scanf("%d%d", &u, &v);
p[u][v] = 1;
}
printf("\n Matrix of input data: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
warshal(p, n);
printf("\n Transitive closure: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
getch();
}
43
OUTPUT:-
RESULT:
44
EX NO : 11
Develop a program to find out the maximum and minimum numbers in a
given list of n numbers using the divide and conquer techniques.
Date:
AIM :
To write a C program to implement divide and conquer techniques.
ALGORITHM :
PROGRAM :
#include <stdio.h>
struct pair {
int min;
int max;
};
45
int mid;
if (low == high) {
minmax.max = arr[low];
minmax.min = arr[low];
return minmax;
if (high == low + 1) {
minmax.max = arr[low];
minmax.min = arr[high];
else {
minmax.max = arr[high];
minmax.min = arr[low];
return minmax;
46
mmr = getMinMax(arr, mid + 1, high);
minmax.min = mml.min;
else
minmax.min = mmr.min;
minmax.max = mml.max;
else
minmax.max = mmr.max;
return minmax;
int main()
int arr_size = 6;
47
getchar();
OUTPUT :
Minimum element is 1
Maximum element is 3000
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
48
Implement Merge sort and Quick sort methods to sort an array of elements
EX NO : 12
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
Date:
the time taken versus n.
AIM :
To write a C program to implement the Merge sort and Quick sort methods.
ALGORITHM :
Merge Sort
Step 1 : Start the program.
Step 2 : Suppose we have a given array, then first we need to divide the array into sub
array. Each sub array can store 5 elements.
Step 3: Here we gave the first sub array name as A1 and divide into next two subarray as
B1 and B2.
Step 4:Similarly, the right sub array name as A2 and divide it into next two sub array as
B3 and B4.
Step 5: This process is repeated continuously until the sub array is divided into a single
element and no more partitions may be possible.
Step 6: After that, compare each element with the corresponding one and then start the
process of merging to arrange each element in such a way that they are placed in
ascending order.
Step 7: The merging process continues until all the elements are merged in ascending
order
Step 8 : Stop the program
PROGRAM :
Merge Sort
#include <stdio.h>
//#include <conio.h>
#include <stdlib.h>
49
i = 0;
j = 0;
k = l;
while (i < a1 && j < a2)
{
if (sub1[i] <= sub2[j])
{
arr[k] = sub1[i];
i++;
}
else
{
arr[k] = sub2[j];
j++;
}
k++;
}
/* st represents the first index and end represents the right index of the subarray of arr[] to be
sorted using merge sort. */
void mergeSort(int arr[], int l, int end)
{
if (l < end)
{
int m = l + (end - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, end);
merge(arr, l, m, end);
}
}
50
// Function to print the merge sort.
void mergePrint(int Ar[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d \t", Ar[i]);
printf("\n");
}
int main()
{
int arr[] = { 70, 80, 40, 50, 60, 11, 35, 85, 2 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Predefined Array is
70 80 40 50 60 11 35 85 2
Quick Sort
Algorithm:
Quick Sort
Step 1 : Start the program.
Step 2 : Consider the first element of the list as pivot.
Step 3: Define two variables i and j. Set i and j to first and last elements of the list
respectively.
Step 4: Increment i until list[i] > pivot then stop..
Step 5: Decrement j until list[j] < pivot then stop..
Step 6 If i < j then exchange list[i] and list[j]..
Step 7: Repeat steps 3,4 & 5 until i > j.
Step 8: Exchange the pivot element with list[j] element.
Step 9 : Stop the program
Program:
#include<stdio.h>
#include<conio.h>
51
void quickSort(int [10],int,int);
void main(){
int list[20],size,i;
quickSort(list,0,size-1);
getch();
}
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}
52
OUTPUT:
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
53
EX NO : 13
Implement N Queens problem using Backtracking
Date:
AIM :
PROGRAM :
54
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
return true;
}
55
/* If the queen cannot be placed in any row in
this column col then return false */
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
..Q.
Q...
...Q
.Q..
Particulars Marks Allocated Marks Obtained
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
56
EX NO : 14 Implement any scheme to find the optimal solution for the Traveling
Salesperson problem and then solve the same problem instance using any
Date: approximation algorithm and determine the error in the approximation.
AIM :
To Write a C program to Implement any scheme 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 the program
Step 2 : Start on an arbitrary vertex as current vertex.
Step 3 : Find out the shortest edge connecting current vertex and an unvisited vertex V.
Step 4 : Set current vertex to V.
Step 5 : Mark V as visited.
Step 6: If all the vertices in domain are visited, then terminate.
Step 7 : Go to step 2.
Step 8: The sequence of the visited vertices is the output of the algorithm.
Step 9:Stop the program.
PROGRAM :
#include<stdio.h>
int a[10][10],n,visit[10];
int cost_opt=0,cost_apr=0;
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_opt(city);
if(ncity==999)
57
ncity=1;
printf("%d",ncity);
cost_opt+=a[city][ncity];
return;
mincost_opt(ncity);
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_apr(city);
if(ncity==999)
ncity=1;
printf("%d",ncity);
cost_apr+=a[city][ncity];
return;
mincost_apr(ncity);
int least_opt(int c)
58
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<min)
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
if(min!=999)
cost_opt+=kmin;
return nc;
int least_apr(int c)
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<kmin)
59
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
if(min!=999)
cost_apr+=kmin;
return nc;
void main()
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visit[i]=0;
60
for(i=1;i<=n;i++)
printf("\n\n");
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
mincost_opt(1);
printf("%d",cost_opt);
for(i=1;i<=n;i++)
visit[i]=0;
mincost_apr(1);
printf("\nMinimum cost:");
printf("%d",cost_apr);
(float)cost_apr/cost_opt);
61
OUTPUT :
0 1 3 6
1 0 2 3
3 2 0 1
6 3 1 0
Optimal Solution :
The path is :
1-->2-->4-->3-->1
Minimum cost:8
Approximated Solution :
The path is :
1-->2-->3-->4-->1
Minimum cost:10
62
Particulars Marks Allocated Marks Obtained
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
63
EX NO : 15
Implement randomized algorithms for finding the kth smallest number. The
programs can be implemented in C/C++/JAVA/ Python.
Date:
AIM :
To Write a C program to implement randomized algorithms for finding the kth smallest
number.
ALGORITHM :
PROGRAM :
// Driver's code
int main()
{
64
int arr[] = { 12, 3, 5, 7, 19 };
int N = sizeof(arr) / sizeof(arr[0]), K = 2;
// Function call
printf("K'th smallest element is %d",
kthSmallest(arr, N, K));
return 0;
}
OUTPUT:
Performance 50
Viva-Voce 10
Record 15
Total 75
RESULT:
65