0% found this document useful (0 votes)
133 views

Lab Record-Cs3401 Algorithms

The document describes an algorithms laboratory course for computer science students. It includes the course objectives, topics to be covered like searching, sorting, graph algorithms, algorithm design techniques, and state space search algorithms. It provides examples of exercises to be done in each topic and the tools to be used.

Uploaded by

sambhvathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Lab Record-Cs3401 Algorithms

The document describes an algorithms laboratory course for computer science students. It includes the course objectives, topics to be covered like searching, sorting, graph algorithms, algorithm design techniques, and state space search algorithms. It provides examples of exercises to be done in each topic and the tools to be used.

Uploaded by

sambhvathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

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

COMPUTER SCIENCE AND ENGINEERING

Cs3401 ALGOrIThMs LABOrATOrY

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

COMPUTER SCIENCE AND ENGINEERING

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

This is to certify that this is a bonafide record of the work done by


Mr./Ms.___________________________________________of IInd YEAR/ IV SEM B.E-
Computer Science and Engineering in Cs3401-ALGOrIThMs LABOrATOrY during the
Academic year 2022 – 2023.

Faculty-in-charge Head of the Department

Submitted for the University Practical Examination held on:

Internal Examiner External Examiner

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.

Cs3401 ALGOrIThMs LABOrATOrY

COURSE OUTCOMES

CO1 Analyze the efficiency of algorithms using various frameworks.

CO 2 Apply graph algorithms to solve problems and analyze their efficiency.

Make use of algorithm design techniques like divide and conquer,


CO 3
dynamic programming and greedy techniques to solve problems.

CO 4 Use the state space tree method for solving problems.

Solve problems using approximation algorithms and randomized


CO 5
algorithms

iv
Cs3401 ALGOrIThMs LABOrATOrY
INDEX

Ex. Page
Date Name of the Exercise Sign
No.
No.

Searching and Sorting Algorithms


1
1. Implementation of Linear Search

2. Implementation of Recursive Binary Seach 4

3. Pattern Searching using Naive algorithm 8

4. (a) Implementation of Insertion sort method to


11
sort a given set of elements.

Implementation of Heap sort method to


(b) 15
sort a given set of elements.

Graph Algorithms
20
5. Implementation of graph traversal using
Breadth First Search

6. Implementation of graph traversal using


24
Depth First Search

7. Finding the shortest paths of a given


vertex in a weighted connected graph to 27
other vertices using Dijkstra’s algorithm

8. Finding the Minimum Cost Spanning Tree


of given undirected graph using Prim’s 31
algorithm

9. Implementation of Floyd’s algorithm for the


34
All-Pairs-Shortest-Paths problem

v
10. Computation of transitive closure of a
given directed graph using Warshall’s 39
algorithm

Algorithm Design Techniques

11. Finding out the maximum and minimum 45


numbers in a given list using the divide
and conquer technique

12.(a) Implementation of Merge sort method to


49
sort an array of elements

(b) Implementation of Quick sort method to


sort an array of elements 54

State Space Search Algorithms

13. Implementation of N Queens problem 58


using Backtracking

14. Algorithms Randomized Algorithms

Implementation of any scheme to find the


optimal solution for the Traveling
Salesperson problem and solve the 62
problem using any approximation
algorithm and determine the error in
approximation

15. Implementation of randomized algorithms


68
for finding the Kth smallest number

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

Tools: C/C++/JAVA/ Python.

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.

Algorithm Design Techniques


1. Develop a program to find out the maximum and minimum numbers in a given list of n
numbers using the divide and conquer technique.
2. 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.

State Space Search Algorithms


1. Implement N Queens problem using Backtracking.

Approximation Algorithms Randomized Algorithms


1. 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.
2. Implement randomized algorithms for finding the kth smallest number.

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:

STEP 1: set pos = -1


STEP 2: set i = 1

STEP 3: repeat step 4 while i <= n

STEP 4: if a[i] == val

set pos = i

print pos

go to step 6

[end of if]

set i = i + 1

[end of loop]

STEP 5: if pos = -1

print "value is not present in the array "


[end of if]

STEP 6: exit

1
PROGRAM/SOURCE CODE:

//C program to implement Linear Search

#include <stdio.h>

#include <time.h>

int linearSearch(int a [], int n, int val)

// Going through array sequentially

for (int i = 0; i < n; i++)

if (a[i] == val)

return i + 1;

return -1;

int main()

int a[20], n, val, i;

clock_t start, end;

double total;

printf("Enter the Number of elements: ");

scanf("%d", &n);

printf("Enter the elements of the array: ");

// loop for the input of elements from 0 to number of elements-1

for (i = 0; i < n; i++)

scanf("%d", &a[i]);

2
printf("Enter the element to search ie. key element: ");

scanf("%d", &val);

start = clock();

int res = linearSearch(a, n, val); // Store result

end = clock();

total = (double)(end - start) / CLOCKS_PER_SEC;

if (res == -1)

printf("\nKey Element is not found in the array");

else

printf("\nKey Element is found at position %d of array using Linear Search", res);

printf("\nTime taken by CPU is %f", total);

return 0;

OUTPUT:
Enter the Number of elements: 5

Enter the elements of the array: 22 34 98 56 44

Enter the element to search ie. key element: 56

Key Element is found at position 4 of array using Linear Search

Time taken by CPU is 0.000003

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 binarySearch(int a[], int beg, int end, int val)

int mid;

if (end >= beg)

mid = (beg + end) / 2;

/*if the item to be searched is present at middle */

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

else if (a[mid] < val)

return binarySearch(a, mid + 1, end, val);

/*if the item to be searched is greater than middle, then it can only be in right
subarray */

else

5
{

return binarySearch(a, beg, mid - 1, val);

return -1;

int main ()

int a[20], n, val, i;

clock_t start, finish;

double total;

printf("Enter the Number of elements: ");

scanf("%d", &n);

printf("Enter the elements of the array: ");

// loop for the input of elements from 0 to number of elements-1

for (i = 0; i < n; i++)

scanf("%d", &a[i]);

printf("Enter the element to search ie. key element: ");

scanf("%d", &val);

start = clock();

int res = binarySearch(a, 0, n - 1, val); // Store result

finish = clock();

total = (double)(finish - start) / CLOCKS_PER_SEC;

6
if (res == -1)

printf("\nKey Element is not found in the array");

else

printf("\nKey Element is found at position %d of array using Binary Search", res);

printf("\nTime taken by CPU is %f", total);

return 0;

OUTPUT:
Enter the Number of elements: 10

Enter the elements of the array: 22 55 11 98 67 21 43 81 32 41

Enter the element to search ie. key element: 81

Key Element is found at position 8 of array using Binary Search

Time taken by CPU is 0.000002

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:

Algorithm Naive(T[1....n], P[1...m])

//Problem Description: This Algorithm finds the string matching using Naive method

//Input: The array text T and pattern P

for i←0 to n-m do

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

Enter the Text: AABAACAADAABAAABAA

Enter the Pattern: AABA

Pattern found at index 0

Pattern found at index 9

Pattern found at index 13

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

//C program to sort elements using Insertion sort

#include <stdio.h>

#include<time.h>

void insert(int a[], int n) /* function to sort an array with insertion sort */

int i, j, temp;

for (i = 1; i < n; i++) {

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;

void printArr(int a[], int n) /* function to print the array */

int i;

for (i = 0; i < n; i++)

printf("%d ", a[i]);

12
}

int main()

int a[10],n,i;

clock_t start, end;

printf("Enter the Number of elements: ");

scanf("%d", &n);

printf("Enter the elements to be sorted: ");

for (i = 0; i < n; i++)

scanf("%d", &a[i]);

double total;

printf("Before sorting array elements are - \n");

printArr(a, n);

start=clock();

insert(a, n);

end=clock();

printf("\nAfter sorting array elements using insertion sort are - \n");

printArr(a, n);

total = (double)(end - start) / CLOCKS_PER_SEC;

printf("\nTime taken by CPU is %f", total);

return 0;

13
OUTPUT:

Enter the Number of elements: 10

Enter the elements to be sorted: 10 55 45 25 15 75 85 65 50 70

Before sorting array elements are -

10 55 45 25 15 75 85 65 50 70

After sorting array elements using insertion sort are -

10 15 25 45 50 55 65 70 75 85

Time taken by CPU is 0.000007

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 1: Construct max heap from given set of elements.


STEP 2: Swap the root key with the last node key of the heap.
STEP 3: Delete the last node and store this key at the end of the array in which heap is
stored.

STEP 4: Heapify the remaining heap structure.

STEP 5: Repeat step 2 to 4 until the last remaining node.

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:

//C program to sort elements using Heap sort

#include <stdio.h>

#include <time.h>

/*function to heapify a subtree. Here 'i' is the

index of root node in array a[], and 'n' is the size of heap. */

void heapify(int a[], int n, int i)

int largest = i; // Initialize largest as root

int left = 2 *i + 1; // left child

int right = 2 *i + 2; // right child

// If left child is larger than root

if (left < n && a[left] > a[largest])

largest = left;

// If right child is larger than root

if (right < n && a[right] > a[largest])

largest = right;

// If root is not largest

if (largest != i)

// swap a[i] with a[largest]

int temp = a[i];

a[i] = a[largest];

a[largest] = temp;

heapify(a, n, largest);

16
}

/*Function to implement the heap sort*/

void heapSort(int a[], int n)

for (int i = n / 2 - 1; i >= 0; i--)

heapify(a, n, i);

// One by one extract an element from heap

for (int i = n - 1; i >= 0; i--)

/*Move current root element to end*/

// swap a[0] with a[i]

int temp = a[0];

a[0] = a[i];

a[i] = temp;

heapify(a, i, 0);

/*function to print the array elements */

void printArr(int arr[], int n)

for (int i = 0; i < n; ++i)

printf("%d", arr[i]);

printf(" ");

17
}

int main()

int a[10], n, i;

clock_t start, end;

printf("Enter the Number of elements: ");

scanf("%d", &n);

printf("Enter the elements to be sorted: ");

for (i = 0; i < n; i++)

scanf("%d", &a[i]);

double total;

printf("Before sorting array elements are - \n");

printArr(a, n);

start = clock();

heapSort(a, n);

end = clock();

printf("\nAfter sorting array elements using heap sort are - \n");

printArr(a, n);

total = (double)(end - start) / CLOCKS_PER_SEC;

printf("\nTime taken by CPU is %f", total);

return 0;

18
OUTPUT:

Enter the Number of elements: 6

Enter the elements to be sorted: 55 44 66 22 77 33

Before sorting array elements are -

55 44 66 22 77 33

After sorting array elements using heap sort are -

22 33 44 55 66 77

Time taken by CPU is 0.000003

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:

To develop a program to implement graph traversal using Breadth First Search.

ALGORITHM:

STEP 1: Consider the graph to navigate.

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.

 Visited array (size of the graph)


 Queue data structure
STEP 4: Add the starting vertex to the visited array, and afterward, add v’s adjacent
vertices to the queue data structure.

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

int n, adj[max][max], visited[max];

void bfs();

void readmatrix();

void main() {

int source;

printf("Enter the source vertex:");

scanf("%d", & source);

readmatrix();

bfs(source);

void readmatrix() {

int i, j;

printf("Enter number of vertices:");

scanf("%d", & n);

printf("Enter the adjacency matrix:\n");

for (i = 1; i <= n; i++)

for (j = 1; j <= n; j++)

scanf("%d", & adj[i][j]);

for (i = 1; i <= n; i++)

21
visited[i] = 0;

void bfs(int source) {

int queue[max];

int i, front, rear, root;

printf("The Breadth First Search sequence is: \n");

front = rear = 0;

visited[source] = 1;

queue[rear++] = source;

printf("%d ", source);

while (front != rear) {

root = queue[front];

for (i = 1; i <= n; i++)

if (adj[root][i] && !visited[i]) {

visited[i] = 1;

queue[rear++] = i;

printf("%d ", i);

front++;

22
OUTPUT:

Enter the source vertex:1


Enter number of vertices:4
Enter adjacency matrix:
0110
1001
1001
0110
The Breadth First Search sequence is:
1234

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:

To develop a program to implement graph traversal using Depth First Search.

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.

STEP 4: Keep repeating steps 2 and 3 until the stack is empty.

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

printf("Enter number of vertices:");

scanf("%d", & n);

printf("Enter the adjacency matrix:\n");

for (i = 1; i <= n; i++) {

for (j = 1; j <= n; j++) {

scanf("%d", & graph[i][j]);

visited[i] = 0;

for (i = 1; i <= n; i++) {

if (visited[i] == 0) {

dfs(i);

void dfs(int l) {

visited[l] = 1;

printf("Node visited is %d\n", l);

25
for (k = 1; k <= n; k++) {

if (visited[k] == 0 && graph[l][k] == 1) {

dfs(k);

OUTPUT:
Enter number of vertices:4

Enter the adjacency matrix:

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

int n, cost[15][15], i, j, s[15], v,dist[15],num,min;

printf ("Enter the number of vertices:\n");

scanf ("%d",&n);

printf ("Enter the cost of the edges:\n");

printf ("Enter 999 if the edge is not present or for the self loop\n");

for (i = 1; i<= n; i++)

for (j = 1; j<= n; j++)

scanf ("%d", &cost[i][j]);

printf ("Enter the Source vertex:\n");

scanf ("%d", &v);

for (i = 1; i<= n; i++)

s[i] = 0;

dist[i] = cost[v][i];

s[v] = 1;

dist[v] = 0;

for (num = 2; num <= n - 1; num++)

min = 999;

28
for (i = 1; i<= n; i++)

if (s[i] == 0 &&dist[i]<min)

min = dist[i];

j = i;

s[j]= 1;

for (i = 1; i<= n; i++)

if (s[i] == 0)

if (dist[i] >(dist[j] + cost[j][i]))

dist[i] = (dist[j] + cost[j][i]);

printf ("VERTEX\tDESTINATION\tCOST\n");

for (i = 1; i<= n; i++)

printf ("%d\t %d\t\t %d\n", v, i, dist[i]);

29
OUTPUT:

Enter the number of vertices:

Enter the cost of the edges:

Enter 999 if the edge is not present or for the self loop

999 4 8 999 999

4 999 1 3 999

8 1 999 7 3

999 3 7 999 8

999 999 3 8 999

Enter the Source vertex:

VERTEX DESTINATION COST

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 1: Start the program.

STEP 2: Initialize the algorithm by choosing the source vertex.

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;

int visited[10] = {0}, min, mincost = 0, cost[10][10];

void main() {

printf("\n Enter the number of vertices:");

scanf("%d", & n);

printf("\n Enter the adjacency matrix:\n");

for (i = 1; i <= n; i++)

for (j = 1; j <= n; j++) {

scanf("%d", & cost[i][j]);

if (cost[i][j] == 0)

cost[i][j] = 999;

visited[1] = 1;

printf("\n");

while (ne < n) {

for (i = 1, min = 999; i <= n; i++)

for (j = 1; j <= n; j++)

if (cost[i][j] < min)

if (visited[i] != 0) {

min = cost[i][j];

a = u = i;

b = v = j;

}
32
if (visited[u] == 0 || visited[v] == 0) {

printf("\nEdge %d:(%d %d)cost:%d", ne++, a, b, min);

mincost += min;

visited[b] = 1;

cost[a][b] = cost[b][a] = 999;

printf("\nThe cost of Minimum Spanning Tree=%d", mincost);

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:

// C program for All-Pairs-Shortest-Paths problem using 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]);

// Solves the all-pairs shortest path

// problem using Floyd Warshall algorithm

void floydWarshall(int dist[][V])

int i, j, k;

/* Add all vertices one by one to

the set of intermediate vertices.

---> Before start of an iteration, we

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


35
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];

// Print the shortest distance matrix

printSolution(dist);

/* A utility function to print solution */

void printSolution(int dist[][V])

printf("The following matrix shows the shortest distances"

" between every pair of vertices \n");

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {


36
if (dist[i][j] == INF)

printf("%7s", "INF");

else

printf("%7d", dist[i][j]);

printf("\n");

// driver's code

int main()

//Creating the following weighted graph

int graph[V][V] = { { 0, 5, INF, 10 },

{ INF, 0, 3, INF },

{ INF, INF, 0, 1 },

{ INF, INF, INF, 0 } };

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

INF INF INF 0

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:

// C program to compute transitive closure using Floyd Warshall Algorithm

#include<stdio.h>

// Number of vertices in the graph

#define V 4

// A function to print the solution matrix

void printSolution(int reach[][V]);

// Prints transitive closure of graph[][] using Floyd Warshall algorithm

void transitiveClosure(int graph[][V])

/* reach[][] will be the output matrix

// that will finally have the

shortest distances between

every pair of vertices */

int reach[V][V], i, j, k;

/* Initialize the solution matrix same

as input graph matrix. Or

we can say the initial values of

shortest distances are based

on shortest paths considering

no intermediate vertex. */

40
for (i = 0; i < V; i++)

for (j = 0; j < V; j++)

reach[i][j] = graph[i][j];

/* Add all vertices one by one to the

set of intermediate vertices.

---> Before start of a iteration,

we have reachability values 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 a iteration,

vertex no. k is added to the

set of intermediate vertices

and the set becomes {0, 1, .. k} */

for (k = 0; k < V; k++)

// Pick all vertices as

// source one by one

for (i = 0; i < V; i++)

41
{

// Pick all vertices as

// destination for the

// above picked source

for (j = 0; j < V; j++)

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

(reach[i][k] && reach[k][j]);

// Print the shortest distance matrix

printSolution(reach);

/* A utility function to print solution */

void printSolution(int reach[][V])

42
printf ("The following matrix is the transitive closure of the given graph: \n");

for (int i = 0; i < V; i++)

for (int j = 0; j < V; j++)

/* because "i==j means same vertex"

and we can reach same vertex

from same vertex. So, we print 1....

and we have not considered this in

Floyd Warshall Algo. so we need to

make this true by ourself

while printing transitive closure.*/

if(i == j)

printf("1 ");

else

printf ("%d ", reach[i][j]);


}
printf("\n");
}

// Driver Code

int main()

43
{

//Creating the following weighted graph

int graph[V][V] = { {1, 1, 0, 1},

{0, 1, 1, 0},

{0, 0, 1, 1},

{0, 0, 0, 1}

};

// Print the solution

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

MergeSort function algorithm:

Merge function 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:

Quick Sort function algorithm:

quickSort(array, leftmostIndex, rightmostIndex)


if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)

Partition function algorithm:


partition(array, leftmostIndex, rightmostIndex)
set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1

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:

To solve N Queens problem using backtracking.

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.

STEP 3: Else try all columns in the current row.

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 -

Enter number of Queens:4

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:

STEP 1: Start the program

STEP 2: First of all, we must create two primary data holders.

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.

STEP 5: Stop the program

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 least_apr(int c);

int least_opt(int c);

void mincost_opt(int city)

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

void mincost_apr(int city)

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

printf("Enter the cost matrix\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]);
}

printf("\n\n Optimal Solution :\n");

printf("\n The path is :\n");

mincost_opt(1);

printf("\n Minimum cost:");

printf("%d",cost_opt);

printf("\n\n Approximated Solution :\n");

for(i=1;i<=n;i++)

visit[i]=0;

printf("\n The path is :\n");

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:

To implement randomized algorithms for finding the kth smallest number .

ALGORITHM:

STEP 1: Take the input of the data set.

STEP 2: Take the input of the value of k.

STEP 3: Call Partition().

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.

STEP 9: Inside main(), print the kth smallest element.

STEP 10: Exit

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

Enter element 10: 2

Enter the k for the kth smallest element: 4

The kth smallest element: 3

RESULT:
Thus the C program to implement randomized algorithms for finding the kth smallest
number has been executed successfully.

71

You might also like