Algorithms Manual r21
Algorithms Manual r21
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 pathsto 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.
AIM
To write a C program for the implementation of Linear Search and to determine the time required to search for an element
ALGORITHM
Step 4: Set i to i + 1
Step 5: Go to step 2
Step 8: stop
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 20
int pos;
int linsearch (int,int[],int);
void main( )
{
int ch=1; double t;
int n,i,a [max],k,op,low,high,pos; clock_tbegin,end;
clrscr();
while(ch)
{ printf("\n. ..... MENU \n 1. Linear search \n 2.Exit \n"); al mitosit thi printf("\n enter your choice\n"); scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter the number of elements \n");
scanf("%d",&n);
printf("\n enter the elements of an array\n");
for(i=0;i<n;i++) scanf("%d",&a[i]);
printf("\n enter the element to be searched \n");
scanf("%d",&k); begin-clock();
pos-linsearch(n,a,k);
end=clock();
if(pos=-1)
printf("\n\n Unsuccessful search");
else
printf("element %d is found at position %d",k,pos+1); printf("\n Time taken is %lf CPU cycles \n", (end-begin)/CLK_TCK);
getch();
break;
default:printf("Invalid choice entered \n"); exit(0);
} printf("\n Do you wish to run again(1/0) \n");
scanf("%d",&ch);
}
getch();
}
int linsearch(int n,int a[],int k)
{
delay(1000);
if(n<0) return -1;
if(k=a[n-1])
return (n-1);
else
return linsearch(n-1,a,k);
}
OUTPUT
.MENU......
.Linear search
.Exit
enter your choice
1
enter the number of elements
enter the number of an array in the order
3
25 69 98
enter the elements to be searched
98
element 98 is found at position 3 Time Taken is 1.978022 CPU1 cycles
RESULT
Thus, the C program to implement linear search was executed and verified.
EX.NO:2 IMPLEMENTATION OF RECURSIVE BINARY SEARCH
AIM
To write a C program for the implementation of recursive binary search and to determine the
time required to search for an element
ALGORITHM
Step 1: Start
Step 2: Compare the target element with the middle element of the array.
Step 2:If the target element is greater than the middle element, then the search continues in the right
half.
Step 3: Else if the target element is less than the middle value, the search continues in the left half.
Step 4:This process is repeated until the middle element is equal to the target element, or the target
element is not in the array
Step 5:If the target element is found, its index is returned, else -1 is returned.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 20
int pos;
Int binsearch (int,int[],int,int,int);
void main()
{
int ch-1:
double t;
int n,i,a [max],k,op.low,high.pos;
clock_tbegin,end;
clrscr());
while(ch)
{ printf("\n...... MENU \n 1.BinarySearch \n 2.Exit \n");
printf("\n enter your choice\n");
scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter the number of elments\n");
scanf("%d",&n); printf("\n enter the number of an array in the order \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the elements to be searched \n");
scanf("%d",&k); low=0;high=n-1; begin=clock();
pos=binsearch(n,a,k,low,high);
end-clock();
if(pos=-1) printf("\n\nUnsuccessful search");
else
printf("\n element %d is found at position %d",k,pos+1);
printf("\n Time Taken is %lf CPU1 cycles \n",(end-begin)/CLK_TCK);
getch();
break;
}
printf("\n Do you wish to run again(1/0) \n");
scanf("%d",&ch);
}
getch();
Int binsearch(int n,int a[],int k,int low,int high)
}
{ int mid; delay(1000); mid=(low+high)/2;
if(low>high) return -1;
if(ka[mid]) return(mid);
else
if(k<a[mid])
return binsearch(n,a,k,low,mid-1);
else return binsearch(n,a,k,mid+1,high);
}
OUTPUT
.BinarySearch
.Exit
enter your choice
1
enter the number of elements
3
enter the number of an array in the order
98
2 22
46
enter the elements to be searched
22 22
element 22 is found at position 2
Time Taken is 1.978022 CPU cycles
RESULT
Thus the C program to implement Binary search was executed and verified successfully.
EX.NO:3 IMPLEMENTATION OF PATTERN SEARCH
AIM
ALGORITHM
Step 1 : Start
Step 2 : O (N*m) where N is size of string and m is size of pattern
Step 3: start at index = 0 (idx_i) to N and create a sub-loop from 0 to m (idx_j)
Step 4: str[idx_j] == pat[idx_j] continue , else break and increment idx_i
Step 5: if any of idx_j == m then the pattern is fully if satisfied and note the idx_i in match array
Step 6:Return the array
Step 8:Stop
PROGRAM
#include <stdio.h>
#include <string.h>
int match(char [], char []);
int main()
{
char a[100], b[100];
int position;
printf("Enter some text\n");
gets(a);
printf("Enter a string to find\n");
gets(b);
position = match(a, b);
if (position != -1) {
printf("Found at location: %d\n", position + 1);
}
else
{
printf("Not found.\n");
}
return 0;
}
int match(char text[], char pattern[])
{
int c, d, e, text_length, pattern_length, position = -1;
text_length = strlen(text);
pattern_length = strlen(pattern);
if (pattern_length > text_length) {
return -1;
}
for (c = 0; c <= text_length - pattern_length; c++)
{
position = e = c;
for (d = 0; d < pattern_length; d++) {
if (pattern[d] == text[e]) {
e++;
}
else {
break;
}
}
if (d == pattern_length) {
return position;
}
}
return -1;
}
OUTPUT
txt="AABAACAADAABAABA"
pat="AABA"
naive_pattern_search(pat, txt)
print("Example-2:")
txt = "abracadabra"
pat = "ab"
naive_pattern_search(pat, txt)
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Example-2:
Pattern found at index 0
Pattern found at index 7 (11 and 1 day next
RESULT
Thus, the C program for pattern search was executed and verified successfully.
EX.NO:4 IMPLEMENTATION OF INSERTION SORT & HEAP SORT
AIM
To Write a C Program to implement Insertion sort & determine the time required to sort the elements.
ALGORITHM
Step 1: Start
Step 2:Create a heap with the input data.
Step 3:Sort the elements of the heap are sorted in ascending order.
Step 4:Swap the root node with the last node and delete the last node from the heap
Step 5: Stop
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<time.h>
void heapsort(int n,int arr[]);
void heapy(int n,int arr[]);
void adjust(int n,int arr[]);
void heapsort(int n,int arr[])
{ inti,item;
delay(100); heapy(n,arr);
for(i=n;i>=1;i--)
{ item=arr[1]; arr[1]=arr[i]; arr[i]=item;
adjust(i,arr);
}
} void heapy(int n,int arr[])
{
inti,j,k,item;
for(i=1;i<=n;i++)
{
item=arr[i]; j=i;
k=j/2;
while(k!=0 && item>arr[k])
{
arr[j]=arr[k]; j-k;
k-j/2; 2560 m of gaier stasmask fe
}
arr[j]=item;
}
void adjust(int n,int arr[])
{
inti,j,item; j=1;
item=arr[j]; i=j*2;
while(i<n)
{
if((i+1)<n)
{
if(arr[i]<arr[i+1])
i++;
}
if(item<<arr[i])
{
arr[j]=arr[i]; j=i;
i=2*j;
}
else break;
}
arr[j]=item;
}
void main
{
int i,n,arr[20];
clock_tend,start;
clrscr();
scanf("%d",&arr[i]);
start=clock();
heapsort(n,arr);
end-clock();
printf("\nSorted Elements are\n");
for(i=1;i<=n;i++) printf("%d ",arr[i]);
printf("\nTime taken by Heapsort %f CPU Cycle", (end-start)/CLK_TCK);
getch();
}
INSERTION SORT
#include <time.h>
#include <stdio.h>
int i;
// Function to print an array
void printArray(int array[], int size) {
for ( i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
void insertionSort(int array[], int size) {
int step;
for (step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
float begin,end;
begin=clock();
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
end=clock();
printf("\n Time Taken is %f CPU1 cycles \n",(end-begin)/CLK_TCK);
}
OUTPUT
Enter the number of Elements: 3
Enter the 3 Elements: 42
85
58
Sorted Elements are
42 58 85
Time taken by Heapsort 0.109890 CPU Cycle_
RESULT
Thus, the program in C for Heap sort was executed and verified successfully.
EX.NO:5 IMPLEMENTATION OF BREADTH FIRST SEARCH
AIM
To write a C program to implement graph traversal using Breadth First Search
ALGORITHM
2. Start by putting any one of the graph's vertices at the back of a queue.
3. Take the front item of the queue and add it to the visited list.
4. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40CE];
int front;
int rear;
};
struct queue* createQueue();
void enqueue(struct queue* q, int); int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q); void printQueue(struct queue* q);
struct node{
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph { int num Vertices;
struct node** adjLists; qang realms of zeng & color
int* visited;
};
// BFS algorithm
void bfs(struct Graph graph, int startVertex) { struct queue* q = createQueue();
graph->visited[startVertex] = 1; enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int current Vertex = dequeue(q);
printf("Visited %d\n", currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while (temp) {
int adj Vertex = temp->vertex;
if (graph->visited[adjVertex] = 0) { graph->visited[adjVertex] = 1;
enqueue(q, adj Vertex);
}
temp = temp->next;
}
}
}
// Creating a node
abo struct node* newNode = malloc(sizeof(struct node));
struct node* createNode(int v) {
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) { struct Graph graph = malloc(sizeof(struct Graph)); graph-
>num Vertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->visited = malloc(vertices *
sizeof(int));
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 struct node*
newNode = createNode(dest); newNode->next = graph->adj Lists[src]; graph->adjLists[src] =
newNode; (vinDsbostess for
// Add edge from dest to src newNode = createNode(src); newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Create a queue
struct queue* createQueue() { struct queue* q = malloc(sizeof(struct queue)); q->front = -1;
q->rear = -1;
return q;
}
// Check if the queue is empty int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}
// Adding elements into queue
void enqueue(struct queue* q, int value) { (pop the
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front=-1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
// Removing elements from queue int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) { printf("Queue is empty");
item = -1;
} else {
item=q->items[q->front];
q->front++;
if (q->front>q->rear) {
printf("Resetting queue");
q->front=q->rear = -1;
}
}
return item;
}
// Print the queue
void printQueue(struct queue* q) {
int i = q->front;
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;
}
Output
Queue contains
0 Resetting queue Visited 0
Queue contains
21 Visited 2
Queue contains
1 4 Visited 1
Queue contains
43 Visited 4
Queue contains
3 Resetting queue Visited 3
RESULT
Thus, the C program to implement graph traversal using Breadth First search was successfully
executed.
EX.NO:6 IMPLEMENTATION OF DEPTH FIRST SEARCH
AIM
To write a C program to implement graph traversal using Depth First Search
ALGORITHM
1. start the program
2. One of the standard rule before starting with DFS algorithm is that DFS puts each vertex of graph
into two categories i.e. Visited & Non Visited.
3. Keeping in mind that each vertex is visited at least once without making cycles.
4. First, need to put any one graph vertices on top of the stack
5. Need to take a top item of the stack and get it added to the visited list
6. Then, create a list of vertex adjacent nodes and add the ones which are not in the visited list to the
top of the stack
7. Just keep repeating the above step 4 & step 5 until the stack gets emptied.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node{
int vertex;
struct node next;
};
struct node* createNode(int v);
struct Graph {
int numVertices;
int* visited;
// We need int** to store a two dimensional array.
// Similary, we need struct node** to store an array of Linked lists struct node** adj Lists;
};
// DFS algo
void DFS(struct Graph* graph, int vertex) { struct node* adjList = graph->adj Lists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1; printf("Visited %d\n", vertex);
while (temp!= NULL) { int connectedVertex temp->vertex;
if (graph->visited[connected Vertex] == 0) {
DFS(graph, connected 'Vertex);
}
temp temp->next;
/ Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
J/Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->visited = malloc(vertices *
sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adj Lists[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 struct node*
newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] =
newNode;
// Add edge from dest to src newNode = createNode(src); newNode->next = graph->adjLists[dest];
graph->adj Lists[dest] = newNode;
}
// Print the graph
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v<graph->num Vertices; v++) { struct node* temp = graph->adj Lists[v]; printf("\n
Adjacency list of vertex %d\n", v); printf("%d ->", temp->vertex); temp = temp->next;
while (temp) {
}
printf("\n");
}
}
int main({
struct Graph graph = createGraph(4); addEdge(graph, 0, 1); addEdge(graph, 0, 2);
addEdge(graph, 1, 2); addEdge(graph, 2, 3); DES(graph, 2);
print Graph(graph);
return 0;
OUTPUT
Adjacency list of vertex 0
2→1→>
Adjacency list of vertex 1
2-0->
Adjacency list of vertex 2
3→1→0→
Adjacency list of vertex 3
2->
Visited 2
Visited 3.
Visited 1
Visited 0
RESULT
Thus ,the program to implement graph traversal using Depth First Search has been successfully
implemented and verified.
EXNO:7 IMPLEMENTATION OF SHORTEST PATH USING DIJKSTRA’S
ALGORITHM
AIM
To develop a program to find the shortest paths to the other vertices from a given vertex in a weighted
connected graph using dijkstra’s algorithm.
ALGORITHM
1. start the program.
2. Create a set sptSet (shortest path tree set) that keeps track of vertices included in the shortest-path
tree.
3. Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first.
4. While sptSet doesn’t include all vertices
Pick a vertex u which is not there in sptSet and has a minimum distance value.
Include u to sptSet.
5. Then update distance value of all adjacent vertices of u.
7. For every adjacent vertex v, if the sum of the 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.
8. stop the program.
PROGRAM
#include <stdio.h>
#define INFINITY 9999
#define MAX 10
void Dijkstra(int Graph[MAX][MAX], int n, int start);
void Dijkstra(int Graph[MAX][MAX], int n, int start) {
int cost[MAX][MAX], distance[MAX], pred[MAX]; int visited[MAX], count, mindistance, nextnode,
i, j;
// Creating cost matrix
for (i=0; i < n; i++)
for (i=0;j< n; j++)
if (Graph[i][j]=0) cost[i][j]=INFINITY;
else
cost[i][j]= Graph[i][j];
for (i=0; i < n; i++) {
distance[i]=cost[start][i];
pred[i] = start;
visited[i] = 0;
}
distance[start] = 0;
visited[start] = 1;
count = 1;
while (count <n-1) { mindistance = INFINITY;
for (i=0; i < n; i++)
if (distance[i] <mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}
visited[nextnode] = 1;
for (i=0; i<n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i]) {
distance[i]= mindistance + cost[nextnode][i];
pred[i]= nextnode;
}
count++;
}
// Printing the distance
for (i=0; i < n; i++)
if (i!= start) {
printf("\nDistance from source to %d: %d", i, distance[i]);
}
}
int main() {
int Graph[MAX][MAX], i, j, n, u;
n = 7;
Graph[0][0] = 0;
Graph[0][1] = 0;
Graph[0][2] = 1;
Graph[0][3] = 2;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 0;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 3;
Graph[1][6]= 0;
Graph[2][0] = 1;
Graph[2][1]=2;
Graph[2][2] = 0;
Graph[2][3] = 1;
Graph[2][4]= 3;
Graph[2][5]=0;
Graph[2][6]=0;
Graph[3][0] = 2;
Graph[3][1]=0;
Graph[3][2] = 1;
Graph[3][3] = 0;
Graph[3][4] = 0;
Graph[3][5] = 0;
Graph[3][6] = 1;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 3;
Graph[5][0] = 0;
Graph[5][1] = 3;
Graph[6][0] = 0;
Graph[6][1] 0;
u = 0;
Dijkstra(Graph, n, u);
return 0;
}
OUTPUT
Distance from source to 1:3
Distance from source to 2: 1
Distance from source to 3:2
Distance from source to 4: 4
Distance from source to 5: 4
Distance from source to 6: 3
RESULT
Thus , the program to find the shortest paths to the other vertices from a given vertex in a weighted
connected graph using dijkstra’s algorithm has been successfully executed and verified.
EXNO: 8 IMPLEMENTATION OF MINIMUM COST SPANNING TREE USING PRIM'S ALGORITHM
AIM
To write a C program to find the minimum cost spanning tree of a given undirected graph using
Prim’s algorithm.
ALGORITHM
1. Start the program.
2. Initialize the minimum spanning tree with a vertex chosen at random.
3. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree
4. Keep repeating step 2 until we get a minimum spanning tree
5. Stop the program.
PROGRAM
#include<stdio.h>
#include<stdbool.h>
#define INF 9999999
// number of vertices in graph
#define V 5
//for adjacency matrix to represent graph
// create a 2d array of size 5x5 int G[V][V] = {
{0, 9, 75, 0, 0},
(9,0,95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};
int main() {
int no_edge; // number of edge
// create a array to track selected vertex
// selected will become true otherwise false
int selected[V];
// set selected false initially
memset(selected, false, sizeof(selected));
// set number of edge to 0
no_edge = 0;
1:5 or soluce il sost
// the number of egde in minimum spanning tree will bevor most expe
// always less than (V-1), where V is number of vertices in TROT SO
//graph
// choose Oth vertex and make it true
selected[0]= true;
int x; // row number
int y; // col number
// print for edge and weight printf("Edge: Weight\n");
while (no_edge <V-1) {
//For every vertex in the set S, find the all adjacent vertices Il, calculate the distance from the vertex
selected at step 1. // if the vertex is already in the set S, discard it otherwise //choose another vertex
nearest to selected vertex at step 1.
int min = INF;
x=0; y=0;
for (int i=0; i<V; i++) {
if (selected[i]) {
for (int j=0;j<V; j++) {
if (!selected[j] && G[i][j]) { // not in selected and there is an edge
if (min > G[i][j]) {
min = G[i][j];
x = i;
y=j;}}}}
printf("%d-%d: %d\n", x, y, G[x][y]);
selected[y]= true;
no_edge++;
}return 0;}
OUTPUT
Edge: Weight
0-1:9
1-3:19
3-4:31
3-2:51
RESULT Thus , C program to find the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm was executed successfully.
EXNO:9 IMPLEMENTATION OF FLOYD'S ALGORITHM
AIM
To develop a program in C to implement floyd’s algorithm for all-pairs-shortest-paths problems.
ALGORITHM
1. Start the program.
2. Create a matrix A0 of dimension n*n where n is the number of vertices. The row and the column
are indexed as i and j respectively. i and j are the vertices of the graph.
3. Now, create a matrix A1 using matrix A0 . The elements in the first column and the first row are
left as they are. The remaining cells are filled in the following way.
4. Similarly, A2 is created using A1. The elements in the second column and the second row are left
as they are.
5. Similarly, A3 and A4 is also created.
6. A4 gives the shortest path between each pair of vertices.
7. Stop the program.
PROGRAM
#include<iostream>
#include<iomanip>
#define NODE 7
#define INF 999
using namespace std;
//Cost matrix of the graph
int costMat[NODE][NODE] = {
{0, 3, 6, INF, INF, INF, INF}, (3, 0, 2, 1, INF, INF, INF},
{6, 2, 0, 1, 4, 2, INF},
{INF, 1, 1, 0, 2, INF, 4},
{INF, INF, 4, 2, 0, 2, 1},
{INF, INF, 2, INF, 2, 0, 1},
{INF, INF, INF, 4, 1, 1, 0}
};
void floyd Warshal(){ int cost[NODE][NODE]; //defind to store shortest distance from any node to
any node
for(int i=0; i<NODE; i++)
for(int j=0; j<NODE; j++)
cost[i][j] costMat[i][j]; //copy costMatrix to new matrix
for(int k = 0; k<NODE; k++){
for(int i=0; i<NODE; i++) for(int j=0; j<NODE; j++)
if(cost[i][k]+cost[k][j] < cost[i][j])
cost[i][j] cost[i][k]+cost[k][j];
}
cout<<"The matrix:"<<<< endl;
for(int i=0; i<NODE; i++){
for(int j = 0; j<NODE; j++)
cout << setw(3) << cost[i][j];
cout << endl;
}
}
int main(){
floyd Warshal();
}
OUTPUT
The matrix:
0354677
3021344
5201323
4110233
6332021
7423201
7433110
RESULT
Thus the C program to implement floyd’s algorithm for all-pairs-shortest-paths problems was
PROGRAM
#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;
for (i=0; i<V; i++)
for (j=0;j<V; j++) reach[i][j] = graph[i][j];
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 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])
{ printf("Following matrix is transitive");
printf("closure of the given graph\n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j<V;j++)
{
if(i == j)
printf("1 ");
printf("%d ", reach[i][j]);
else}
printf("\n"); }}
int main()
{/* Let us create the following weighted graph
10
(0)
>(3)
51
W
(1)-
3
int graph[V][V]= { {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}};// Print the solution transitive Closure(graph); return 0;}
OUTPUT
Following matrix is transitive closure of the given graph
1111
0111
0011
0001
RESULT Thus the program to compute the transitive closure of the given directed graph warshall’s
algorithm was implemented successfully.
EXNO:11 IMPLEMENTATION OF DIVIDE AND CONQUER TECHNIQUE
AIM
To develop a program to find the minimum and maximum numbers in a given list of n numbers using
divide and conquer technique.
ALGORITHM
1. Start the program.
2. Let us consider simple problem that can be solved by the divide-and conquer technique.
3. The problem is to find the maximum and minimum value in a set of ‘n’ elements.
4. By comparing numbers of elements, the time complexity of this algorithm can be analyzed.
5. Hence, the time is determined mainly by the total cost of the element comparison.
6. Stop the program.
PROGRAM
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
void findMinAndMax(vector<int> const &nums, int low, int high, int &min, int
&max)
{
if (low == =high)
{
// common comparison
if (max < nums[low]) {
// comparison
max = nums[low];
}
if (min> nums[high]) {
// comparison 2
min = nums[high];
return;
}
if (high-low == 1)
// common comparison
{
if (nums[low] < nums[high])
// comparison 1
{
if (min> nums[low]) {
min = nums[low];
// comparison 2 MIRODA
supist sampoos bee hivi di gaien de lot &
if (max < nums[high]) {
max= nums[high];
// comparison 3
}
}
else {
if (min> nums[high]) {
minnums[high];
}
if (max < nums[low]) {
// comparison 3
max = nums[low];
}
// comparison 2
}
return;
}
int mid = (low + high)/2;
findMinAndMax(nums, low, mid, min, max);
findMinAndMax(nums, mid + 1, high, min, max);
}
int main()
{
vector<int> nums = {7, 2, 9, 3, 1, 6, 7, 8, 4};
int max = INT_MIN, min INT_MAX;
int n=nums.size();
findMinAndMax(nums, 0, n - 1, min, max);
cout <<"The minimum array element is "<< min << endl; cout <<"The maximum array element is
"<< max << endl;
return 0;
}
OUTPUT
The minimum array element is 1 The maximum array element is 9
RESULT
Thus , the C program to find the minimum and maximum numbers in a given list of n numbers using
divide and conquer technique was implemented successfully.
EXNO:12 IMPLEMENTATION OF MERGE SORT AND QUICK SORT
AIM
To implement the C program for Merge Sort and Quick Sort
ALGORITHM
Step 1 :if it is only one element in the list it is already sorted, return.
Step 2 :divide the list recursively into two halves until it can no more be divided.
Step 3: merge the smaller lists into new list in sorted order.
Step 4 :Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 5 : Define two variables i and j. Set i and j to first and last elements of the list respectively.
Step 6 : Increment i until list[i] > pivot then stop.
Step 7 : Decrement j until list[j] < pivot then stop.
Step 8 : If i < j then exchange list[i] and list[j].
Step 9 : Repeat steps 3,4 & 5 until i > j.
Step 10 : Exchange the pivot element with list[j] element.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int 1, int m, int r)
{ int i, j, k; int nl m-1+1; int n2 = r - m; int L[nl], R[n2];
for (i=0; i<nl; i++)
L[i] = arr[1 + i); for (i=0;j<n2; j++)
R[j]= arr[m+1+j];
i=0; // Initial index of first subarray
j=0; // Initial index of second subarray k=1; // Initial index of merged subarray
while (i<nl && j <n2) {
if (L[i] <<=R[j]) {
arr[k]-L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;}
while (i<nl) {
arr[k] = L[i];
i++;
k++;}
while (j <n2) {
arr[k] = R[j];
j++;
k++;}}
void mergeSort(int arr[], int I, int r)
if (l<r) {
int m-1+(r-1)/2;
// Sort first and second halves mergeSort(arr, 1, m); mergeSort(arr, m + 1, r); in argidong anomaly
merge(arr, l, m, r);
:((bred," be "nung}}
void printArray(int A[], int size) { int i; for (i=0; i < size; i++)
printf("%d", A[i]); printf("\n"); } {
int main( )
int arr[] = { 12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/ sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);,
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;}
OUTPUT
Given array is
12 11 13 567
Sorted array is
567 11 12 13
RESULT
Thus, the C program for merge sort and Quick sort was executed and verified successfully
EXNO:13 IMPLEMENTATION OF N QUEENS PROBLEM USING BACKTRACKING.
AIM
ALGORITHM
1. Initialize an empty chessboard of size NxN.
2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a queen
in the current column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules of the
problem, backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7 until all possible configurations have been tried.
#define N 4
#include <stdbool.h>
#include <stdio.h>
void printSolution(int board[N][N]) {
for (int i = 0; i < N; i++) { for (int j=0;j<N; j++) printf("%d", board[i][j]); printf("\n");
}
(asiz niyaтAng lov }
bool isSafe(int board[N][N], int row, int col
{
int i, j;
for (i=0; i < col; i++)
if (board[row][i])
return false;
for (i= row, j = col; i >= 0 && j>= 0; i--, j--) (_á_nr]žen
if (board[i][j])
return false;
for (i= row, j col; j> 0 && i < N; i++, j-) if (board[i][j])
return false;
return true;
} bool solveNQUtil(int board[N][N], int col)
{
if (col >= N)
return true;
this queen in all rows one by one */
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1; if (solveNQUtil(board, col + 1))
return true;
CANY board[i][col] = 0; // BACKTRACKODJA MOITAMIXOR
} ilk nel mitulo lendigo of bail os side tus imomolgan?
}
aidong mag atovice gas bus maidong moraln return false; the proroch bas metrogle osmonga
}
bool solveNQO
{
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;
int main( )
{
solveNQO;
return 0; }
OUTPUT
1* no yo ano or in ni dosup zi
RESULT
Thus the c program to Implement N Queens problem using Backtracking was executed and verified.
EXNO:14 IMPLEMENTATION OF APPROXIMATION ALGORITHMS FOR THE TRAVELING
SALESPERSON PROBLEM
AIM
To Implement a program in C for the Traveling Salesperson problem and then solve the same
problem instance using any approximation algorithm and determine the error in the approximation
ALGORITHM
1. Consider city 1 as the starting and ending point. Since the route is cyclic, we can
consider any point as a starting point.
2. Generate all (n-1)! permutations of cities.
3. Calculate the cost of every permutation and keep track of the minimum cost
permutation.
4. Return the permutation with minimum cost.
PROGRAM
#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)
{
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;
}
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 ij;
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);
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.250000
RESULT
Thus the c program To Implement the optimal solution for the traveling Salesperson problem was
executed and verified.
EXNO:15 IMPLEMENTATION OF RANDOMIZED ALGORITHMS FOR FINDING THE
KTH SMALLEST NUMBER
AIM
To Implement randomized algorithms for finding the kth smallest number
ALGORITHM
1) Divide arr[] into ⌈n/5⌉ groups where size of each group is 5 except possibly the last group which
may have less than 5 elements.
2) Sort the above created ⌈n/5⌉ groups and find median of all groups. Create an auxiliary array
‘median[]’ and store medians of all ⌈n/5⌉ groups in this median array.
// Recursively call this method to find median of median[0..⌈n/5⌉-1]
3) medOfMed = kthSmallest(median[0..⌈n/5⌉-1], ⌈n/10⌉)
4) Partition arr[] around medOfMed and obtain its position.
pos = partition(arr, n, medOfMed)
5) If pos == k return medOfMed
6) If pos > k return kthSmallest(arr[l..pos-1], k)
7) If pos < k return kthSmallest(arr[pos+1..r], k-pos+l-1)
PROGRAM
#include<iostream>
#include<climits>
#include<cstdlib>
using namespace std;
int randomPartition(int arr[], int 1, int r);
int kthSmallest(int arr[], int 1, int r, int k)
return kthSmallest(arr, 1, pos-1, k);
return kthSmallest(arr, pos+1, r, k-pos+1-1);
}
return INT_MAX;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b= temp;
}
int partition(int arr[], int 1, int r)
{
int x = arr[r], i=1; for (int j = 1; j <=r-1; j++)
{
if (arr[j] <= x)
{
swap(&arr[i], &arr[j]);
i++; } } swap(&arr[i], &arr[r]); return i;
}
int randomPartition(int arr[], int 1, int r)
{
int n=r-1+1;
int pivot = rand()% n;
swap(&arr[1+ pivot], &arr[r]); return partition(arr, 1, r);
}
int main(
{
int arr[]= {12, 3, 5, 7, 4, 19, 26};
int n = sizeof(arr)/sizeof(arr[0]), k = 3; cout <<"K'th smallest element is "<<kthSmallest(arr, 0, n-1,
k);
return 0;
}
OUTPUT
K'th smallest element is 5
RESULT
Thus the c program to Implement randomized algorithms for finding the kth smallest number was
executed and verified