Lab Record-Cs3401 Algorithms
Lab Record-Cs3401 Algorithms
DEPARTMENT
OF
REGULATION-2021
NAME :
REGISTER NUMBER :
YEAR : II
SEMESTER : IV
i
MISRIMAL NAVAJEE MUNOTH JAIN ENGINEERING COLLEGE
OWNED AND MANAGED BY TAMILNADU EDUCATIONAL AND MEDICAL FOUNDATION
A JAIN MINOrITY INsTITUTION
ApprOvED BY AICTE &prOGrAMMEs ACCrEDITED BY NBA, NEW DELhI, (UG prOGrAMMEs – MECh, EEE, ECE, CsE & IT)
ALL prOGrAMMEs rECOGNIzED BY ThE GOvErNMENT OF TAMIL NADU AND AFFILIATED TO ANNA UNIvErsITY, ChENNAI
GUrU MArUDhArKEsArI BUILDING, JYOThI NAGAr, rAJIv GANDhI sALAI, OMr ThOrAIpAKKAM, ChENNAI - 600 097.
DEPARTMENT
OF
VISION
Producing competent Computer Engineers with a strong background in the latest
trends and technology to achieve academic excellence and to become pioneer in
software and hardware products with an ethical approach to serve the society.
MISSION
To provide quality education in Computer Science and Engineering with the state
of the art facilities. To provide the learning audience that helps the students to
enhance problem solving skills and to inculcate in them the habit of continuous
learning in their domain of interest. To serve the society by providing insight
solutions to the real world problems by employing the latest trends of computing
technology with strict adherence to professional and ethical responsibilities.
ii
MISRIMAL NAVAJEE MUNOTH JAIN ENGINEERING COLLEGE
OWNED AND MANAGED BY TAMILNADU EDUCATIONAL AND MEDICAL FOUNDATION
A JAIN MINOrITY INsTITUTION
ApprOvED BY AICTE &prOGrAMMEs ACCrEDITED BY NBA, NEW DELhI, (UG prOGrAMMEs – MECh, EEE, ECE, CsE & IT)
ALL prOGrAMMEs rECOGNIzED BY ThE GOvErNMENT OF TAMIL NADU AND AFFILIATED TO ANNA UNIvErsITY, ChENNAI
GUrU MArUDhArKEsArI BUILDING, JYOThI NAGAr, rAJIv GANDhI sALAI, OMr ThOrAIpAKKAM, ChENNAI - 600 097.
Register No:
BONAFIDE CErTIFICATE
DATE:
iii
MISRIMAL NAVAJEE MUNOTH JAIN ENGINEERING COLLEGE
OWNED AND MANAGED BY TAMILNADU EDUCATIONAL AND MEDICAL FOUNDATION
A JAIN MINOrITY INsTITUTION
ApprOvED BY AICTE &prOGrAMMEs ACCrEDITED BY NBA, NEW DELhI, (UG prOGrAMMEs – MECh, EEE, ECE, CsE & IT)
ALL prOGrAMMEs rECOGNIzED BY ThE GOvErNMENT OF TAMIL NADU AND AFFILIATED TO ANNA UNIvErsITY, ChENNAI
GUrU MArUDhArKEsArI BUILDING, JYOThI NAGAr, rAJIv GANDhI sALAI, OMr ThOrAIpAKKAM, ChENNAI - 600 097.
COURSE OUTCOMES
iv
Cs3401 ALGOrIThMs LABOrATOrY
INDEX
Ex. Page
Date Name of the Exercise Sign
No.
No.
Graph Algorithms
20
5. Implementation of graph traversal using
Breadth First Search
v
10. Computation of transitive closure of a
given directed graph using Warshall’s 39
algorithm
vi
Cs3401 ALGOrIThMs LABOrATOrY
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
Suggested Exercises:
Searching and Sorting Algorithms
1. 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.
2. 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.
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 txt [ ]. You may assume that n > m.
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 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.
vii
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.
viii
Ex.No: 1
IMPLEMENTATION OF LINEAR SEARCH
Date :
AIM:
To implement Linear Search and determine the time required to search for an element.
ALGORITHM:
set pos = i
print pos
go to step 6
[end of if]
set i = i + 1
[end of loop]
STEP 5: if pos = -1
STEP 6: exit
1
PROGRAM/SOURCE CODE:
#include <stdio.h>
#include <time.h>
if (a[i] == val)
return i + 1;
return -1;
int main()
double total;
scanf("%d", &n);
scanf("%d", &a[i]);
2
printf("Enter the element to search ie. key element: ");
scanf("%d", &val);
start = clock();
end = clock();
if (res == -1)
else
return 0;
OUTPUT:
Enter the Number of elements: 5
RESULT:
Thus the C program to implement Linear Search and to determine the time required to
search for an element has been executed successfully.
3
Ex.No: 2
IMPLEMENTATION OF RECURSIVE BINARY SEARCH
Date :
AIM:
To implement Recursive Binary Search and determine the time required to search for an
element.
ALGORITHM:
STEP 1: set beg = lower_bound, end = upper_bound, pos = - 1
STEP 2: repeat steps 3 and 4 while beg <=end
STEP 3: set mid = (beg + end)/2
STEP 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
STEP 5: if pos = -1
print "value is not present in the array"
[end of if]
STEP 6: exit.
4
PROGRAM/SOURCE CODE:
//C program to implement Recursive Binary Search
#include <stdio.h>
#include <time.h>
int mid;
if (a[mid] == val)
return mid + 1;
/*if the item to be searched is smaller than middle, then it can only be in left
subarray */
/*if the item to be searched is greater than middle, then it can only be in right
subarray */
else
5
{
return -1;
int main ()
double total;
scanf("%d", &n);
scanf("%d", &a[i]);
scanf("%d", &val);
start = clock();
finish = clock();
6
if (res == -1)
else
return 0;
OUTPUT:
Enter the Number of elements: 10
RESULT:
Thus the C program to implement Recursive Binary Search and to determine the time
required to search for an element has been executed successfully.
7
Ex.No: 3
PATTERN SEARCHING USING NAIVE ALGORITHM
Date :
AIM:
To write a program for a given text and pattern and write a search function that prints all
occurrences of pattern in text.
ALGORITHM:
//Problem Description: This Algorithm finds the string matching using Naive method
{
if P[1......m] == T[i+1.....i+m] then
print "Match Found"
} //end of algorithm
8
PROGRAM/SOURCE CODE
// C program for Naive Pattern Searching algorithm
#include <stdio.h>
#include <string.h>
void search(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);
/*A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++)
{
int j;
/*For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
printf("Pattern found at index %d \n", i);
}
}
// Driver's code
int main()
{
char txt[50], pat[50];
int i, j;
printf("\n Enter the Text: ");
gets(txt);
9
printf("\n Enter the Pattern: ");
gets(pat);
// Function call
search(pat, txt);
return 0;
}
OUTPUT:
RESULT:
Thus the C program for a given text and pattern and to write a search function that prints
all occurrences of pattern in text has been executed successfully.
10
Ex.No: 4(a)
IMPLEMENTATION OF INSERTION SORT METHOD
TO SORT A GIVEN SET OF ELEMENTS
Date :
AIM:
To sort a given set of elements using the Insertion sort method 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.
STEP 2: Pick the next element and store it separately in a key.
STEP 3: 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.
11
PROGRAM/SOURCE CODE
#include <stdio.h>
#include<time.h>
void insert(int a[], int n) /* function to sort an array with insertion sort */
int i, j, temp;
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one
position ahead from their current position*/
a[j+1] = a[j];
j = j-1;
a[j+1] = temp;
int i;
12
}
int main()
int a[10],n,i;
scanf("%d", &n);
scanf("%d", &a[i]);
double total;
printArr(a, n);
start=clock();
insert(a, n);
end=clock();
printArr(a, n);
return 0;
13
OUTPUT:
10 55 45 25 15 75 85 65 50 70
10 15 25 45 50 55 65 70 75 85
RESULT:
Thus the C program to sort a given set of elements using the Insertion sort method and
to determine the time required to sort the elements has been executed successfully.
14
Ex.No: 4(b)
IMPLEMENTATION OF HEAP SORT METHOD
Date : TO SORT A GIVEN SET OF ELEMENTS
AIM:
To sort a given set of elements using the Heap sort method and determine the time
required to sort the elements.
ALGORITHM:
STEP 6: Delete the last node and store it in the array of heap.
STEP 7: Print all the elements of the array. This will display the elements in sorted order.
15
PROGRAM/SOURCE CODE:
#include <stdio.h>
#include <time.h>
index of root node in array a[], and 'n' is the size of heap. */
largest = left;
largest = right;
if (largest != i)
a[i] = a[largest];
a[largest] = temp;
heapify(a, n, largest);
16
}
heapify(a, n, i);
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
printf("%d", arr[i]);
printf(" ");
17
}
int main()
int a[10], n, i;
scanf("%d", &n);
scanf("%d", &a[i]);
double total;
printArr(a, n);
start = clock();
heapSort(a, n);
end = clock();
printArr(a, n);
return 0;
18
OUTPUT:
55 44 66 22 77 33
22 33 44 55 66 77
RESULT:
Thus the C program to sort a given set of elements using the Heap sort method
and to determine the time required to sort the elements has been executed
successfully.
19
Ex.No: 5
IMPLEMENTATION OF GRAPH TRAVERSAL
Date : USING BREADTH FIRST SEARCH
AIM:
ALGORITHM:
STEP 2: Select any vertex in the graph (say v), from which the graph needs to be traversed.
STEP 3: The following two data structures are utilized for traversing the graph.
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.
20
PROGRAM/SOURCE CODE:
//C program to implement graph traversal using BFS
#include <stdio.h>
#define max 10
void bfs();
void readmatrix();
void main() {
int source;
readmatrix();
bfs(source);
void readmatrix() {
int i, j;
21
visited[i] = 0;
int queue[max];
front = rear = 0;
visited[source] = 1;
queue[rear++] = source;
root = queue[front];
visited[i] = 1;
queue[rear++] = i;
front++;
22
OUTPUT:
RESULT:
Thus the C program to implement graph traversal using Breadth First Search has been
executed successfully.
23
Ex.No: 6
IMPLEMENTATION OF GRAPH TRAVERSAL
Date : USING DEPTH FIRST SEARCH
AIM:
ALGORITHM:
DFS implementation categorizes the vertices in the graphs into two categories:
Visited
Not visited
STEP 1: Start by pushing starting vertex of the graph into the stack.
STEP 2: Pop the top item of the stack and add it to the visited list.
STEP 3: Create the adjacency list for that vertex. Add the non-visited nodes in the list to the
top of the stack.
24
PROGRAM/SOURCE CODE:
//C program to implement graph traversal using DFS
#include<stdio.h>
int i, j, k, n;
int graph[20][20];
int visited[20];
void dfs(int);
void main() {
visited[i] = 0;
if (visited[i] == 0) {
dfs(i);
void dfs(int l) {
visited[l] = 1;
25
for (k = 1; k <= n; k++) {
dfs(k);
OUTPUT:
Enter number of vertices:4
0110
1001
1001
0110
Node visited is 1
Node visited is 2
Node visited is 4
Node visited is 3
RESULT:
Thus the C program to implement graph traversal using Depth First Search has been
executed successfully.
26
Ex.No: 7 FINDING THE SHORTEST PATHS OF A GIVEN
VERTEX IN A WEIGHTED CONNECTED GRAPH TO
Date :
OTHER VERTICES USING DIJKSTRA’S ALGORITHM
AIM:
To develop a program to find the shortest paths of a given vertex to all the other vertices
using Dijkstra’s algorithm.
ALGORITHM:
Create a shortest path tree set that keeps track of vertices included in shortest path tree, i.e.,
whose minimum distance from source is calculated and finalized. Initially, this set is empty.
- Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE.
- Assign distance value as 0 for the source vertex so that it is picked first.
- While shortest path tree set doesn’t include all vertices
a) Pick a vertex u which is not there in shortest path tree set and has minimum distance
value.
b) Include u to shortest path tree set
c) Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance
value of u (from source) and weight of edge u-v, is less than the distance value of v,
then update the distance value of v.
27
PROGRAM/SOURCE CODE:
//C program to find the shortest paths of a vertex to other vertices using Dijkstra’s
algorithm
#include<stdio.h>
main ()
scanf ("%d",&n);
printf ("Enter 999 if the edge is not present or for the self loop\n");
s[i] = 0;
dist[i] = cost[v][i];
s[v] = 1;
dist[v] = 0;
min = 999;
28
for (i = 1; i<= n; i++)
if (s[i] == 0 &&dist[i]<min)
min = dist[i];
j = i;
s[j]= 1;
if (s[i] == 0)
printf ("VERTEX\tDESTINATION\tCOST\n");
29
OUTPUT:
Enter 999 if the edge is not present or for the self loop
4 999 1 3 999
8 1 999 7 3
999 3 7 999 8
1 1 0
1 2 4
1 3 5
1 4 7
1 5 8
RESULT:
Thus the C program to find the shortest paths of a given vertex to all the other vertices
using Dijkstra’s algorithm has been executed successfully.
30
Ex.No: 8
FINDING THE MINIMUM COST SPANNING TREE OF
GIVEN UNDIRECTED GRAPH USING PRIM’S
Date : ALGORITHM
AIM:
To find the Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
ALGORITHM:
STEP 3: Find the minimum weight edge connected to the source node and another node and
add it to the tree.
STEP 4: Keep repeating this process until we find minimum spanning tree. To write a
shell program to find the sum of n numbers.
31
PROGRAM/SOURCE CODE:
//C program to find Minimum Cost Spanning Tree using Prim’s algorithm
#include<stdio.h>
int a, b, u, v, n, i, j, ne = 1;
void main() {
if (cost[i][j] == 0)
cost[i][j] = 999;
visited[1] = 1;
printf("\n");
if (visited[i] != 0) {
min = cost[i][j];
a = u = i;
b = v = j;
}
32
if (visited[u] == 0 || visited[v] == 0) {
mincost += min;
visited[b] = 1;
OUTPUT:
Enter the number of vertices:6
Enter the adjacency matrix:
030065
301004
010604
006085
600802
544520
Edge 1:(1 2)cost:3
Edge 2:(2 3)cost:1
Edge 3:(2 6)cost:4
Edge 4:(6 5)cost:2
Edge 5:(6 4)cost:5
The cost of Minimum Spanning Tree=15
RESULT:
Thus the C program to find the Minimum Cost Spanning Tree of a given undirected
graph using Prim’s Algorithm has been executed successfully.
33
Ex.No: 9
IMPLEMENTATION OF FLOYD’S ALGORITHM FOR
Date :
THE ALL-PAIRS-SHORTEST-PATHS PROBLEM
AIM:
To implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.
ALGORITHM:
For a graph with N vertices:
STEP 1: Initialize the shortest paths between any 2 vertices with Infinity.
STEP 2: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest
paths that use 1 intermediate vertex and so on.. until using all N vertices as intermediate
nodes.
STEP 3: Minimize the shortest paths between any 2 pairs in the previous operation.
STEP 4: For any 2 vertices (i,j) , one should actually minimize the distances between this
pair using the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).
dist[i][k] represents the shortest path that only uses the first K vertices, dist[k][j] represents
the shortest path between the pair k,j. As the shortest path will be a concatenation of the
shortest path from i to k, then from k to j.
34
PROGRAM/SOURCE CODE:
#include <stdio.h>
#define V 4
int i, j, k;
intermediate vertices.
becomes {0, 1, 2, .. k} */
// dist[i][j]
printSolution(dist);
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
printf("\n");
// driver's code
int main()
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
// Function call
floydWarshall(graph);
return 0;
37
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
RESULT:
Thus the C program to implement Floyd’s algorithm for the All-Pairs-Shortest-Paths
problem has been executed successfully.
38
Ex.No: 10 COMPUTATION OF TRANSITIVE CLOSURE OF A
GIVEN DIRECTED GRAPH USING WARSHALL’S
Date : ALGORITHM
AIM:
To compute the transitive closure of a given directed graph using Warshall’s algorithm.
ALGORITHM:
Algorithm Warshall(A[1..n,1..n])
//Implements Warshall’s algorithm for computing the transitive closure
//Input: The Adjacency matrix A of a digraph with n vertices
//Output: The transitive closure of digraph
{
R (0):= A
for k :=1 to n do
{
for i := 1 to n do
{
for j := 1 to n do
{
R (k)[i,j] := R (k-1)[i,j] or R (k-1)[i,k] and R(k-1)[k,j]
}
}
}
return R(n)
}
39
PROGRAM/SOURCE CODE:
#include<stdio.h>
#define V 4
int reach[V][V], i, j, k;
no intermediate vertex. */
40
for (i = 0; i < V; i++)
reach[i][j] = graph[i][j];
intermediate vertices.
41
{
// If vertex k is on a path
// from i to j,
// of reach[i][j] is 1
reach[i][j] = reach[i][j] ||
printSolution(reach);
42
printf ("The following matrix is the transitive closure of the given graph: \n");
if(i == j)
printf("1 ");
else
// Driver Code
int main()
43
{
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
transitiveClosure(graph);
return 0;
OUTPUT:
The following matrix is the transitive closure of the given graph
1111
0111
0011
0001
RESULT:
Thus the C program to compute the transitive closure of a given directed graph using
Warshall’s algorithm has been executed successfully.
44
Ex.No: 11 FINDING THE MAXIMUM AND MINIMUM NUMBERS
IN A GIVEN LIST USING THE DIVIDE AND CONQUER
Date : TECHNIQUE
AIM:
To develop a program to find out the maximum and minimum numbers in a given list
using the divide and conquer technique.
ALGORITHM:
Algorithm Max_Min_Val(i,j,max,min)
//Problem Description: Finding min, max elements recursively.
//Input: i,j are integers used as index to an array A. The max and min will
//contain maximum and minimum value elements
//Output: None
if (i==j) then
{
max <- A[i];
min <- A[j];
}
else if(i=j-1) then
{
if(A[i]<A[j]) then
{
max <- A[j];
min <- A[i];
}
else
{
max <- A[i];
min <- A[j];
} //end of else
//end of if
}
else
{
mid <- (i+j)/2 //divide the list handling two lists separately
Max_Min_Val(i,mid,max,min)
Max_Min_Val(mid+1, j,max_new, min_new)
if(max<max_new)then
max <- max_new //combine solution
if(max>max_new)then
min <- min_new //combine solution
}
45
PROGRAM/SOURCE CODE:
//C program to find max and min number in a list using divide and conquer technique
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
}
}
else
{
mid = (i+j)/2;
46
maxmin(i, mid);
max1 = max;
min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
}
}
}
int main ()
{
int i, num;
printf ("\nEnter the total number of numbers : ");
scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);
max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in the array : %d\n", min);
printf ("Maximum element in the array : %d\n", max);
return 0;
}
47
OUTPUT:
Enter the total number of numbers : 5
Enter the numbers :
-3 9 10 55 100
Minimum element in the array : -3
Maximum element in the array : 100
RESULT:
Thus the C program to find out the maximum and minimum numbers in a given list using
the divide and conquer technique has been executed successfully.
48
Ex.No: 12(a)
IMPLEMENTATION OF MERGE SORT
Date : METHOD TO SORT AN ARRAY OF ELEMENTS
AIM:
To implement Merge sort method to sort an array of elements and determine the time
required to sort.
ALGORITHM
49
}
PROGRAM/SOURCE CODE:
//C program to sort elements using Merge sort
#include <stdio.h>
#include <time.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end) {
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
50
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0; /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */
while (i < n1 && j < n2) {
if (LeftArray[i] <= RightArray[j]) {
a[k] = LeftArray[i];
i++;
} else {
a[k] = RightArray[j];
j++;
}
k++;
}
while (i < n1) {
a[k] = LeftArray[i];
i++;
k++;
}
while (j < n2) {
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end) {
if (beg < end) {
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
51
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main() {
int a[20], n, i;
clock_t start, end;
double total;
printf("Enter the number of elements:");
scanf("%d", & n);
printf("Enter the elements:");
for (i = 0; i < n; i++)
scanf("%d", & a[i]);
printf("Before sorting array elements are - \n");
printArray(a, n);
start = clock();
mergeSort(a, 0, n - 1);
end = clock();
total = (double)(end - start) / CLOCKS_PER_SEC;
printf("After sorting array elements using merge sort are - \n");
printArray(a, n);
printf("\nTime taken by CPU is %f", total);
return 0;
}
52
OUTPUT:
Enter the number of elements:10
Enter the elements:12 10 24 1 76 31 21 2 99 81
Before sorting array elements are -
12 10 24 1 76 31 21 2 99 81
After sorting array elements using merge sort are -
1 2 10 12 21 24 31 76 81 99
Time taken by CPU is 0.000006
RESULT:
Thus the C program to implement Merge sort method to sort an array of elements and to
determine the time required to sort has been executed successfully.
53
Ex.No: 12(b)
IMPLEMENTATION OF QUICKSORT METHOD
Date : TO SORT AN ARRAY OF ELEMENTS
AIM:
To implement Quick sort method to sort an array of elements and determine the time
required to sort.
ALGORITHM:
54
PROGRAM/SOURCE CODE:
//C program to sort elements using Quick sort
#include <stdio.h>
#include <time.h>
/* function that consider last element as pivot,
place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
int partition(int a[], int start, int end) {
int pivot = a[end]; // pivot element
int i = (start - 1);
for (int j = start; j <= end - 1; j++) {
// If current element is smaller than the pivot
if (a[j] < pivot) {
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i + 1];
a[i + 1] = a[end];
a[end] = t;
return (i + 1);
}
/* function to implement quick sort */
void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end
= Ending index */ {
if (start < end) {
int p = partition(a, start, end); //p is the partitioning index
55
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}
/* function to print an array */
void printArr(int a[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main() {
int a[20], n, i;
clock_t start, end;
double total;
printf("Enter the number of elements:");
scanf("%d", & n);
printf("Enter the elements:");
for (i = 0; i < n; i++)
scanf("%d", & a[i]);
printf("Before sorting array elements are - \n");
printArr(a, n);
start = clock();
quick(a, 0, n - 1);
end = clock();
printf("\nAfter sorting array elements using quick sort are - \n");
printArr(a, n);
printf("\nTime taken by CPU is %f", total);
return 0;
}
56
OUTPUT:
Enter the number of elements:10
Enter the elements:99 21 19 98 76 20 41 2 45 32
Before sorting array elements are -
99 21 19 98 76 20 41 2 45 32
After sorting array elements using quick sort are -
2 19 20 21 32 41 45 76 98 99
Time taken by CPU is 0.000005
RESULT:
Thus the C program to implement Quick sort method to sort an array of elements and to
determine the time required to sort has been executed successfully.
57
Ex.No: 13
IMPLEMENTATION OF N QUEENS PROBLEM
Date : USING BACKTRACKING
AIM:
ALGORITHM:
STEP 1: Place the queen row-wise, starting from the left-most cell.
STEP 2: If all queens are placed then return true and print the solution matrix.
Condition 1 - Check if the queen can be placed safely in this column then mark the
current cell [Row, Column] in the solution matrix as 1 and try to check the rest of the
problem recursively by placing the queen here leads to a solution or not.
Condition 2 - If placing the queen [Row, Column] can lead to the solution return true
and print the solution for each queen's position.
Condition 3 - If placing the queen cannot lead to the solution then unmark this [row,
column] in the solution matrix as 0, BACKTRACK, and go back to condition 1 to try other
rows.
STEP 4: If all the rows have been tried and nothing worked, return false to trigger
backtracking.
58
PROGRAM/SOURCE CODE:
//C program to solve N Queens problem using Backtracking
#include<stdio.h>
#include<math.h>
int board[20], count;
int main()
{
int n, i, j;
void queen(int row, int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d", & n);
queen(1, n);
return 0;
}
//function for printing the solution
void print(int n)
{
int i, j;
printf("\n\nSolution %d:\n\n", ++count);
for (i = 1; i <= n; ++i)
printf("\t%d", i);
for (i = 1; i <= n; ++i)
{
printf("\n\n%d", i);
for (j = 1; j <= n; ++j) //for nxn board
{
if (board[i] == j)
printf("\tQ"); //queen at i,j position
else
59
printf("\t-"); //empty slot
}
}
}
/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row, int column)
{
int i;
for (i = 1; i <= row - 1; ++i)
{
//checking column and diagonal conflicts
if (board[i] == column)
return 0;
else
if (abs(board[i] - column) == abs(i - row))
return 0;
}
return 1; //no conflicts
}
//function to check for proper positioning of queen
void queen(int row, int n)
{
int column;
for (column = 1; column <= n; ++column)
{
if (place(row, column))
{
board[row] = column; //no conflicts so place queen
if (row == n) //dead end
60
print(n); //printing the board configuration
else //try queen with next position
queen(row + 1, n);
}
}
}
OUTPUT:
- N Queens Problem Using Backtracking -
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - -
4 - - Q -
Solution 2:
1 2 3 4
1 - - Q -
2 Q - - -
3 - - - Q
4 - Q - -
RESULT:
Thus the C program to solve N Queens problem using Backtracking has been executed
successfully.
61
Ex.No: 14
IMPLEMENTATION OF APPROXIMATION ALGORITHM
Date : FOR SOLVING TRAVELING SALESPERSON PROBLEM
AIM:
To implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then to solve the same problem instance using any approximation algorithm and
to determine the error in the approximation.
ALGORITHM:
o First of them is a list that can hold the indices of the cities in terms of the input
matrix of distances between cities
o And the Second one is the array which is our result
STEP 3: Perform traversal on the given adjacency matrix tsp[][] for all the city and if the
cost of reaching any city from the current city is less than the current cost the
update the cost.
STEP 4: Generate the minimum path cycle using the above step and return their
minimum cost.
62
PROGRAM/SOURCE CODE:
/*C program to find optimal solution for the Traveling Salesperson problem and to
solve the same using any approximation algorithm and determine the error in the
approximation*/
#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)
ncity=1;
printf("%d",ncity);
cost_opt+=a[city][ncity];
return;
mincost_opt(ncity);
63
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)
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;
}
64
}
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)
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;
65
printf("Enter No. of cities:\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter elements of row:%d\n",i );
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visit[i]=0;
}
printf("The cost list is \n");
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);
66
printf("\n\nError in approximation is approximated solution/optimal solution=%f",
(float)cost_apr/cost_opt);
OUTPUT:
Enter No. of cities: 4
Enter the cost matrix
Enter elements of row:1
0136
Enter elements of row:2
1023
Enter elements of row:3
3201
Enter elements of row:4
6310
The cost list is
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
Error in approximation is approximated solution/optimal solution=1.2500
RESULT:
Thus the C program to implement any scheme to find the optimal solution for the
Traveling Salesperson problem and then to solve the same problem instance using any
approximation algorithm and to determine the error in the approximation has been executed
successfully.
67
Ex.No: 15
IMPLEMENTATION OF RANDOMIZED ALGORITHMS
Date : FOR FINDING THE Kth SMALLEST NUMBER
AIM:
ALGORITHM:
STEP 4: Inside Partition(), rearrange the array according to the pivot using CreatePartition()
STEP 5: Get the new index of the pivot as ‘pindex’ and compare it with (k-1).
STEP 6: If both the values are equal then return the value as a result to the main().
STEP 7: If pindex > k-1, recursively call Partition() for the part before the pivot value.
STEP 8: If pindex < k-1, recursively call Partition() for the part after the pivot value.
68
PROGRAM/SOURCE CODE:
//C program to implement randomized algorithms for finding the Kth smallest number
#include<stdio.h>
// Swapping two values.
void swap(int * a, int * b)
{
int temp;
temp = * a;
* a = * b;
* b = temp;
}
// Partitioning the array on the basis of values at high as pivot value.
int CreatePartition(int a[], int low, int high)
{
int pivot, index, i;
index = low;
pivot = high;
// Getting index of pivot.
for (i = low; i < high; i++)
{
if (a[i] < a[pivot])
{
swap( & a[i], & a[index]);
index++;
}
}
// Swapping value at high and at the index obtained.
swap( & a[pivot], & a[index]);
return index;
}
69
// Implementing Partition.
int Partition(int a[], int low, int high, int k)
{
int pindex;
if (low < high)
{
// Partitioning array using last element as a pivot.
// Recursively implementing partitioning in the direction to place the pivot at (k-1)th
pivot.
pindex = CreatePartition(a, low, high);
if (pindex == k - 1)
return k - 1;
else if (pindex > k - 1)
Partition(a, low, pindex - 1, k);
else
Partition(a, pindex + 1, high, k);
}
}
int main()
{
int n, i, k, kk;
printf("\nEnter the number of data elements: ");
scanf("%d", & n);
int arr[n];
for (i = 0; i < n; i++)
{
printf("Enter element %d: ", i + 1);
scanf("%d", & arr[i]);
}
printf("\nEnter the k for the kth smallest element: ");
70
scanf("%d", & k);
kk = Partition(arr, 0, n - 1, k);
// Printing the result.
printf("\nThe kth smallest element: %d", arr[kk]);
return 0;
}
OUTPUT:
Enter the number of data elements: 10
Enter element 1: 9
Enter element 2: 4
Enter element 3: 0
Enter element 4: 3
Enter element 5: 7
Enter element 6: 8
Enter element 7: 1
Enter element 8: 5
Enter element 9: 6
RESULT:
Thus the C program to implement randomized algorithms for finding the kth smallest
number has been executed successfully.
71