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

Algorithm-Lab Updated

The program implements insertion sort to sort elements of an array and determines the time taken for different sizes of arrays. It takes array size and elements as input, calls the insertion sort function to sort the elements, prints the sorted array and time taken.

Uploaded by

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

Algorithm-Lab Updated

The program implements insertion sort to sort elements of an array and determines the time taken for different sizes of arrays. It takes array size and elements as input, calls the insertion sort function to sort the elements, prints the sorted array and time taken.

Uploaded by

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

lOMoARc PSD|28104798

EXP.NO: 1
IMPLEMENTATION OF LINEAR
SEARCH
DATE:

AIM:
To write a C program for “implementation of linear search”.

ALGORITHM:
1. Start the program

2. Initialize the required variables

3. Declare the position

4. Get the input from the user

5. Enter the search elements

6. If the element is found print”element is found”

7. Give the input from the time taken cpu cycles

8. Display the result

9. Stop the program


lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>

#define max20

int pos;

int Linearsearch(int,int[],int);

void main()
{
Int ch=1;

double t;
int n,i,k,op,pos,a[20];
Clock_t begin,end;
Clrscr();
While(ch)
{
Printf(“\n….MENU……\n1.Linearsearch\n2.Exit\n”);

Printf(“\n enter your choice\n”);

Scanf(“%d”,&op);
Switch(op)
{
case1:
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]);
lOMoARc PSD|28104798
lOMoARc PSD|28104798

Printf(“\n enter the element to be searched\n”);`


Scanf(“%d”,&k);
begin=clock();
pos=Linearsearch(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 %if 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 Linearsearch(int n,int a[],int k)
{
delay(1000);
If(n<0)

return -1;
if(k==a[n1])

return(n-1);

else
return Linearsearch(n-1,a,k);
}
lOMoARc PSD|28104798

OUTPUT:
….MENU….
1.Linearsearch
2.Exit
Enter your choice : 1
Enter the number of elements 3
Enter the number of an array in the order25 69 98
Enter the elements to be searched 98
Element 98 is found atposition 3
Time taken is 1.978022CPU cycles

Value of n Time

3 1.978022

4 2.032967

6 3.956044

8 1.978022

10 3.021978

12 8.956044

14 10.12345

15

10

Value of n Time

Linearsearch
lOMoARc PSD|28104798

RESULT:
Thus the C program “Implementation of Linear search” has been executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX:NO:2
IMPLEMENT RECURSIVE BINARY SEARCH. DETERMINETHETIME
REQUIRED TO SEARCH AN ELEMENT.
DATE:

AIM:
To implement a recursive binary search program and determine the time requiredtosearch an element.

ALGORITHM:
1. start the program.
2. Set the low index to the first element of the array and the high index tothe lastelement.
3. Set the middle index to the average of the low and high indices.
a. If the element at the middle index is the target element, return themiddleindex.
b. Otherwise, based on the value of the key to be found and the valueof themiddle
element, decide the next search space.
i. If the target is less than the element at the middle index, set thehighindex to
middle index – 1.
ii. If the target is greater than the element at the middle index, set thelowindex to
middle index + 1.
4. Perform step 2 repeatedly until the target element is found or the searchspace isexhausted.
5. And also calculate the time complexity.
6. Stop the program.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

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;
doublet;
int n,i,a[20],e,low,high,pos;
clock_tbegin,end;
clrscr();
printf("Enter The Size Of TheArray:");
scanf("%d",&n);
printf("Enter The Elements Of the Array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter The Element To Search");
scanf("%d",&e);
low=0;high=n-1;
begin=clock();
pos=binsearch(n,a,e,low,high);
end=clock();
pos=binsearch(n,a,e,low,high);
end=clock();
if(pos==-1)
printf("Unsuccessfull Search");
else
printf("Element %d found at pos %d",e,pos+1);
printf("\ntime taken is %f if cpu1 cycles",(end-begin)/CLK_TCK);
getch();
}
int binsearch(int n,int a[],int e,int low,int high)
{
int mid; delay(1000);
mid=(low+high)/ 2;
if(low>high)
return -1;
if(e==a[mid])
return(mid);
else
if(e<a[mid])
lOMoARc PSD|28104798

OUTPUT:

Enter the size of thearray:34

Enter the elements of thearray:1

Enter the elements to

search:1Element 1 is foundat 0

Time take is 1.944 CPU cycle


lOMoARc PSD|28104798

return binsearch(n,a,e,low,mid-1);
else
return binsearch(n,a,e,mid+1,high);
}
lOMoARc PSD|28104798

Value ofn Time


(t)

1 1.944

2 2.967

3 0.989

4 3.021
lOMoARc PSD|28104798

RESULT:
The c program to implement the recursive binary search has been executedsuccessfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EXP.NO: 3
FUNCTION SEARCH

DATE:

AIM:
The Aim of this function is to search for all occurrences of a given pattern within given text and print the
indices where the pattern is found

ALGORITHM:

Step 1: Start

Step 2: Loop through the text from index 0 to n-m, where n is the length of thetext and m is the
length of the pattern.

Step 3: For each iteration, check if the substring of text from the current indexto current index +
pattern length is equal to the pattern.

Step 4 : If there's a match, print the index where the pattern is found.

Step 5: Continue looping until all occurrences of the pattern in the text are found
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<string.>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>

void search(char pat[],char txt[])


{
int i,j;
int m = strlen(pat);
int n =strlen(txt);
int count = 0; //To keep track of the number of occurrences

//Iterate through the text


for(int i=0;i<=n-m;i++)
{
int j;

//Check if the current substring matches the patternfor(j=0;j<m;j++)


{
if(txt[i+j] != pat[j])
{
Break;
}
}
if(j==m)
{
}
}
if(count==0)
{
//If the pattern is found, print index and increment the count
printf("Pattern found at index %d\n", i);
count++;

else
{

//If no occurrence found,print a message

printf("Pattern not found intext.\n");

//Print the total count of occurrence


printf("Total occurenes : %d\n",count);
}
lOMoARc PSD|28104798
lOMoARc PSD|28104798

int main()
{
char txt[]="AABAACAADAABAAABAA";
char pat[]="AABA";
printf("Text: %s\n",txt);
printf("Pattern:%s\n",pat);
printf("Occurences:\n");
search(pat,txt);
printf("Time Complexity:O(56)");
getch();

}
lOMoARc PSD|28104798

OUTPUT:
Text: AABAACAADAABAAABAA
Pattern:
AABA
Occurrences:
Pattern found at index
0Pattern found at index
9Pattern found at index 13
Total occurrences: 3Time complexity:O(56)
lOMoARc PSD|28104798

RESULT:

The function search() takes a pattern and a text as input and searches for all occurrences of the
pattern in the text. It then prints the indices where the pattern is found. In the example usage, the
pattern "Abab" Is found at indices0 and 10 in the text "Ababdabacdababcabab"
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EXP.NO: 4(a)
INSERTION SORT

DATE:

AIM:
To write a C program to sort the elements using insertion sort and plot a graphfor the time taken.

ALGORITHM :
1. Start
2. Declare the variables.
3. Get the value of n from the user.

4. Get the elements usingfor loop


5. Call the insertion() function and sort the elements .
6. Print the sorted array and also print the time taken to sort the elements.

7. 7.Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void insertion(int a[],int n)
{

int i,key,j;

for(i=1;i<n;i++)
key=a[i];
j=i-1;
while(j>=0&&a[j]>key)
a[j+1]=a[j];
j=j-1;
}
a[j+1]=key;
}
}
{
int main()
{
int a[50],i,n;
clock_t t;
double time;
t=clock();
printf("enter n\n ");
scanf("%d",&n);
printf("enter elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
insertion(a,n);
t=clock()-t;
printf("sorted elements\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
time=((double)t)/CLOCKS_PER_SEC;
printf("time taken %f sec",time);
return 0;}
lOMoARc PSD|28104798

OUTPUT:
Enter
n3
Enter
elements12234
2
Sorted
elements234
122
Time taken 11.098901 sec

GRAPH:

20
18
16
14
12
10 Series1
Series2

1 2 3 4 5 6
lOMoARc PSD|28104798

RESULT:

Thus the program for insertion sort has been executed successfully along with the time complexity graph.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EXP.NO: 4(b)
HEAP SORT

DATE:

AIM:
To write a c program to sort a set of elements using heap sort and plot a graph of the time taken .

ALGORITHM:
1. start the program
2. declare the variables and functions.
3. get the value of n and elements of the array.
4. using the heapify() function find the larger value and sort them by usingheapsort()function.
5. display the sorted elements and time taken inseconds.
6. 6.stop the program.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:
#include<stdio.h>
#include<time.h>

Void heapify(int*,int,int);

Void heapsort(int *,int);

Voidprint_array(int*,int);

int main()
{
int n,i,a[50];
clock_t t;
double time;
t=clock();
printf("enter the value of n\n");
scanf("%d,&n);
printf("\n enter elements\n");
for(i=0;i<n;i++)
{
scanf("\n %d",&a[i]);
}
heapsort(a,n);
printf("\n\n aftersorting\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
t=clock()-t;
time=((double)t)/CLOCK_PER_SEC;
printf("time taken is %f",time);
return 0;
}
void heapsort(int * a,int n)
{
int i;
for(i=n-1;i>=0;i--)
{
heapify(a,n,i);
}
for(i=n-1;i>=0;i--)
{
int temp=a[i];
a[i]=a[0];
a[0]=temp;
heapify(a,i,0);
lOMoARc PSD|28104798
lOMoARc PSD|28104798

}
void heapify(int*a,int n,int i)
{
int large=i;
int left=2*i+1;
int right=2*i+2;
if(left<n&&a[left]>a[large])
{
large=left;
}
if(right<n&&a[right]>a[large])
{
large=right;
}
if(large!=i)
{
int temp=a[i];
a[i]=a[large];
a[large]=temp;
heapify(a,n,large);
}
}
void print_array(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
lOMoARc PSD|28104798

OUTPUT:
Enter n:5
Enter
element2
345
2
3
67
After sort:
2
3
23
45
67
Time taken:11.703297sec

GRAPH:

20
18
16
14
12
10 Series1
Series2

1 2 3 4 5 6
lOMoARc PSD|28104798

RESULT:
Thus the program for heap sort has been executed successfully along with the timecomplexity graph.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX. NO : 5(a)
BREADTH FIRST SEARCH
DATE:

AIM:
To develop a program to implement graph traversal using breadth first search.

ALGORITHM :
1. Start by putting any one of the graph's vertices at the back of a queue
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the back of the
queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for (i=1;i<=n;i++)
if(a[v][i] &&!visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main ( )
{
int v;
clrscr();
printf("\n Enter the number ofvertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrixform:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachableare:\n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
else
printf("\n Bfs is notpossible");
getch();
}
lOMoARc PSD|28104798

OUTPUT:

Enter the number of vertices:3 Enter


graph data inmatrix form:
010
101
011
Enter the starting vertex:1
The node which are reachable are:1 2 3
lOMoARc PSD|28104798

RESULT:

Thus to develop a program to implement a graph traversal using breadth firstsearch has been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX. NO : 5(b)
DEPTH FIRST SEARCH
DATE:

AIM:

To develop a program to implement graph traversal using depth first search.

ALGORITHM:
1. Start by putting any one of the graph's vertices on top of a stack.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the stack.
4. Keep repeating steps 2 and 3 until the stack is empty.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<conio.h>
int a[20] [20] , reach[20] ,n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] &&!reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main( )
{
inti,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++)
{
if(reach[i]
)
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is notconnected");
getch();

}
lOMoARc PSD|28104798

OUTPUT:

Enter number of vertices:


3Enter the adjacency matrix:
011
101
110
1->2
2->3

Graph is connected
lOMoARc PSD|28104798

RESULT:

Thus to develop a program to implement graph traversal using depth first searchhas been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX. NO : 6(a)
DIJKSTRA’S ALGORITHM
DATE:

AIM:

To develop a program for shortest paths to other vertices using Dijkstra's algorithm.

ALGORITHM:

1. Create a set short path to store vertices that come in the way of the shortest path tree.
2. Initialize all distance values INFINITE and assign distance values as 0 for source vertex so
that it is picked first.
3. Loop until all vertices of the graph are in the short path.
4. Take a new vertex that is not visited and is nearest.
5. Add this vertex to short path .
6. For all adjacent vertices of this vertex update distance. Now check every adjacent vertex of
V, if sum of distance of u and weight of edge is else the update it.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<conio.>

#include<limits.>

#include <stdbool.h>
#include<stdio.h>
#define V 9

int minDistance(int dist[], bool sptSet[])


{
int min = INT_MAX, min_index;

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

if (sptSet[v] == false && dist[v] <=min)

min =dist[v], min_index = v;

return min_index;

}
void printSolution(int dist[])
{

printf("Vertex \t\t Distance from Source\n");


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

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

void dijkstra(int graph[V][V], int src)

int dist[V];

boolsptSet[V]:

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

dist[i] = INT_MAX, sptSet[i] =false;

dist[src] = 0;

for (int count = 0; count < V - 1; count++)

{
lOMoARc PSD|28104798
lOMoARc PSD|28104798

int u = minDistance(dist, sptSet);

sptSet[u]= true;

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

if(!sptSet[v]&&graph[u][v]&&dist[u]!=INT_MAX&&dist[u]+graph[u][v]<dist [v])

dist[v] = dist[u] + graph[u][v];

printSolution(dist);

int main()

int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },

{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },

{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },

{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },

{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },

{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },

{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },

{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },

{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

dijkstra(graph,0);

getch();

return 0;

}
lOMoARc PSD|28104798

GRAPH:

OUTPUT:
lOMoARc PSD|28104798

RESULT:

Thus the program for develop the shortest paths to other vertices using dijkstra’salgorithm has been
executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX. NO : 6(b)
PRIMS’S ALGORITHM
DATE:

AIM

To write the program for minimum cost spanning tree of a given undirected graph
using prims algorithm.

ALGORITHM:

1. Determine an arbitrary vertex as the starting vertex of the MST.


2. Follow steps 3 to 5 till there are vertices that are not included in the
MST
(known as fringe vertex).
3. Find edges connecting any tree vertex with the fringe vertices.
4. Find the minimum among these edges.
5. Add the chosen edge to the MST if it does not from any cycle.
6. Return the MST and exit.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<limits.h>
#include<stdbool.h>
#defineV 5

int minKey(int key[], bool mstSet[])


{
int min = INT_MAX, min_index;

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


if (mstSet[v] == false && key[v] < min)min =key[v],min_index = v;
return min_index;
}
int printMST(int parent[], int graph[V][V])
{
printf("Edge\tWeight\n");
for(int i = 1; i< V; i++)
printf("%d - %d \t%d \n",parent[i], i, graph[i][parent[i]]);
}

void primMST(int graph[V][V])


{
int parent[V];

int key[V];

bool mstSet[V];

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


key[i] = INT_MAX,
mstSet[i] = false;
key[0] =0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++)


{
int u= minKey(key, mstSet);
mstSet[u] =true;
for (int v = 0; v < V; v++)
if (graph[u][v] &&mstSet[v] == false&&graph[u][v] <key[v]) parent[v] = u, key[v] =
graph[u][v];
}

printMST(parent, graph);
}
lOMoARc PSD|28104798
lOMoARc PSD|28104798

int main()
{

int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

primMST(graph);
getch();
Return 0;
}
lOMoARc PSD|28104798

GRAPH:

OUTPUT:
lOMoARc PSD|28104798

RESULT:

Thus the program for find the minimum cost spanning tree using prim’s algorithm has been executed
successefully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX. NO : 7(A)
FLOYD’S ALGORITHM
DATE:

Aim:

To implement floyd’s Algorithm for all pairs shortest path problem

Algorithm:

1. Start the program


2. Initialize the solution matrix same as the input graph matrix as a first step.
3. Then update the solution matrix by considering all vertices as an intermediatevertex.
4. The idea is to one by one pick all vertices and updates all shortest paths whichinclude the picked
vertex as an intermediate vertex in the shortest path.
5. When we pick vertex number k as an intermediate vertex, we already haveconsidered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
6. For every pair (I, j) of the source and destination vertices respectively, thereare two possible
cases.
7. K is not an intermediate vertex in shortest path from I to j. We keep the valueof dist[i][j] as it is.
8. K is an intermediate vertex in shortest path from I to j. We update the value ofdist[i][j] as
dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]
9. Display the result
10. Exit
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:
#include <stdlib.h>
void floydWarshall(int **graph, int n)
{
int i, j, k;
for (k = 0; k < n; k++)
{

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


{
for (j = 0; j < n; j++)
{
if (graph[i][j] > graph[i][k] + graph[k][j])
graph[i][j] = graph[i][k] + graph[k][j];
}

int main(void)
{
int n, i, j;
int**graph=(int**)malloc((long unsigned)n*sizeof(int*));
printf(“Enter the number of vertices: “);

scanf(“%d”, &n); for (i = 0; i < n; i++)


{
graph[i] = (int *)malloc((long unsigned) n * sizeof(int));
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j) graph[i][j] = 0;
else
graph[i][j] = 100;
}
}
printf(“Enter the edges: \n”);

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


{
for (j = 0; j < n; j++)
{
lOMoARc PSD|28104798

Output:
Enter the number of vertices: 4
Enter the edges:
[0][0]: 2

[0][1]: 4

[0][2]: 5

[0][3]: 6

[1][0]: 1

[1][1]: 0

[1][2]: 0

[1][3]: 4

[2][0]: 4

[2][1]: 7

[2][2]: 8

[2][3]: 9

[3][0]: 0

[3][1]: 5

[3][2]: 8

[3][3]: 9

The original graph is:

2456

1004
lOMoARc PSD|28104798

printf(“[%d][%d]: “, i, j);
scanf(“%d”, &graph[i][j]);

}
printf(“The original graph is:\n”);
for (i = 0; i< n; i++)
{
for (j = 0; j < n; j++)
{
printf(“%d “, graph[i][j]);
}
printf(“\n”);
}
floydWarshall(graph, n);
printf(“The shortest path matrix is:\n”);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf(“%d “, graph[i][j]);
}
printf(“\n”);
}
return 0;

}
lOMoARc PSD|28104798

4789

0589

The shortest path matrix is:2 4 4 6

1004

4779

0446
lOMoARc PSD|28104798

Result:

Thus to implement floyd’s algorithm for all pairs shortest path problem has beenhas been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 7(B)

WARSHALL’S ALGORITHM

DATE:

Aim:
To compute the transitive closure of a directed graph using warshall
algorithm.

Algorithm:
1. Start the program
2. Initialize the variables and graph
Here we use warshall algorithm to compute the transitive closure of the directed graph

3. Warshall algorithm has two rules


4. Rule 1: If an element in row I and column J is 1 in R(k-1)remains 1 in
R(k)
Rule 2: an element in row I and column j is 0 in R(k-1) it has toto 1 In R(k) it has to be

changed to 1 in R if and only if (k) if be changed

5. The element in its row I and column k and the element


6. In its column j and row k are both 1’s in
7. Display the result
8. Exit
lOMoARc PSD|28104798
lOMoARc PSD|28104798

Program:

#include<stdio.h>
const int MAX = 100;
void WarshallTransitiveClosure(int graph[MAX], int numVert);int main(void)
{
int I,j,numVert;
int graph[100][100];
printf(“Enter the number of vertices:”);
scanf(“%d”,&numVert);
printf(“Enter the adajacency matrix:-\n”);
for(i=0;i<numVert;i++) for(j=0;j<numVert;j++);
scanf(“%d”,&graph[i][j]);

WarshallTransitiveClosure(graph,numVert);

printf(“\nThe Transitive closure for the given graph is :- \n);


for(i=0;i<numvert;i++)
{
for(j=0;j<numVert;j++)
{
printf(“%d\t”,graph[i][j]);
}
}
printf(“\n”);
}
return 0;
}
void WarhsallTransitiveClosure(int graph[MAX][MAX],int numVert)
{
int I,j,k;
for(k=0;k<numVert;k++)

{
for(i=0;i<numvert;i++)
{
for(j=0;j<numVert;j++)
{
if(graph[i][j] || (graph[i][k]&&graph[k][j]))
graph[i][j]=1;
}
}
}
}
lOMoARc PSD|28104798

OUTPUT:

Warshall’s Transitive ClosureEnter

the number of vertices:4Enter the

adjacency Matrix:- 1 0 0 0

1001

1100

1100

1010

The transitive closure for the given graph is:-

1 0 0 0

1 1 1 1

1 1 1 1
lOMoARc PSD|28104798

RESULT:

Thus to compute the transitive closure of the directed graph usingwarshall algorithm has been
executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 8
DIVIDE AND CONQUER TECHNIQUE
DATE:

AIM:

To find the maximum and minimum numbers in given list of n numbersusing divide and
conquer technique

ALGORITHM:

1. Set min and max to arr[0]

2. Start loop at 1, using index i

a) Check if arr[i] < min; if so, set min to arr[i]

b) Check if arr[i]>max; is so, set max to arr[i]

3. At the end of the loop, respond with and array

4. If the array is 1 element long, return [arr[0], arr[0]]

5. If the array is 2 elements long if arr[0] > arr[1], return [arr[1], arr[0]]

6. Otherwise, return arr

7. Split the array roughly into a left hald, calling minmax on each half

8. Return [min(left[0],right[0]), max(left[1],right[1]]


lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM

#include<stdio.h>
struct pair
{
Int min;
Int max;
};
Struct pair getMinMax(int arr[], int n)
{
Struct pair minmax;Int I;
If (n == 1)
{
Minmax.max = arr[0];
Minmax.min = arr[0];
Return minmax;
}
If (arr[0] > arr[1])
{

Minmax.max = arr[0];
Minmax.min = arr[1];

}
Else
{
Minmax.max = arr[1];
Minmax.min = arr[0];
}
For (I = 2; i<n; i++)
{
If (arr[i] > minmax.max) Minmax.max = arr[i];
Else if (arr[i] < minmax.min) Minmax.min = arr[i];
}
Return minmax;
}
Int main()
{
Int arr[] = {1000, 11, 445, 1, 330, 3000};
Int arr_size = 6;
Struct pair minmax = getMinMax (arr, arr_size);
Printf(“nMinimum element is %d”, minmax.min);
Printf(“nMaximum element is %d”, minmax.max);
Getchar();
Return 0;
}
lOMoARc PSD|28104798

OUTPUT:

nMinimum Element is 1

nMaximum Element is 3000


lOMoARc PSD|28104798

RESULT:

Thus the program for finding maximum and minimum number of nnumbers using
divide and conquer technique was executed successfully
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 9(a)
MERGE SORT
DATE:

AIM:

To implement a merge sort to sort an array of elements

ALGORITHM:

1. Start the program

2. Declare array and left, right and mid values

3. Find the middle index of the array to divide int two half

4. Find mid=(left+right)/2

5. Call mergesort on (left,mid) and (right,n-mid)

6. Calculate the time taken to sort

7. Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include <stdio.h>
#include <time.h>
// Function to merge two sorted arrays
void merge(int arr[], int left[], int left_size, int right[], int right_size)
{
int i = 0, j = 0, k = 0;
while (i < left_size && j < right_size)
{
if (left[i] < right[j])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while (i < left_size) arr[k++] = left[i++];
while (j < right_size) arr[k++] = right[j++];
}
// Function to perform merge sortvoid
mergeSort(int arr[10], int n)
{
if (n <= 1) return;
int mid = n / 2;
int left[10];
int right[20];
// Dividing the array into left and right halves
for (int i = 0; i < mid; i++)
left[i] = arr[i];
for (int i = mid; i < n; i++)
right[i - mid] = arr[i];
// Recursively sorting left and right halvesm
mergeSort(right, n - mid);
// Merging the sorted left and right halves
merge(arr, left, mid, right, n - mid);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[10];
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nOriginal Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Recording the start time
clock_t start = clock();
mergeSort(arr, n);
// Recording the end time
clock_t end = clock();
printf("\nSorted Array: ");
lOMoARc PSD|28104798
lOMoARc PSD|28104798

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


printf("%d ", arr[i]);
printf("\n");
// Calculating the time taken to sort
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nTime taken to sort: %f seconds\n", time_taken);
return 0;
}mergeSort(left, mid);

mergeSort(right, n - mid);
// Merging the sorted left and right halves
merge(arr, left, mid, right, n -mid);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[10];
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nOriginal Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Recording the start time
clock_t start = clock();
mergeSort(arr, n);
// Recording the end time
clock_t end = clock();
printf("\nSorted Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Calculating the time taken to sort
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nTime taken to sort: %f seconds\n", time_taken);
return 0;
}
lOMoARc PSD|28104798

OUTPUT:

Enter the number of elements: 3Enter

the elements: 28 41 47

Original array: 28 41 47

Sorted array: 28 41 47

Time taken to sort: 0.000002


lOMoARc PSD|28104798

RESULT:

Thus to implement a merge sort to sort an array elements hasbeen executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 9(b)
QUICK SORT
DATE:

AIM:

To implement a quick sort to sort an array of elements

ALGORITHM:

1. Start the program

2. Declare an array

3. Pick an element from an array, call it as pivot element

4. Divide an unsorted array into two array

5. If values less than pivot element come under first subarray

6. If value greater than pivot element come under second subarray

7. Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<stblib.h>
#include<time.h>
void swap(int*a, int*b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int partition(int arr[],int low,int high)
{
int pivot=arr[low];
int i=low+1;int
j=high; while(1)
{
while(i<=j&&arr[i]<pivot)
i++;
while(i<=j&&arr[j]>pivot)
j--;
if(i<=j)
{
swap(&arr[i],&arr[j]);
i++;
j--;
}
else
break;
}
swap(&arr[low],&arr[j]);
return j;
}
void quicksort(int arr[],int low,int high)
{
if(low<high)
{
int pivotIndex=partition(arr,low,high);
}
}
int main()
{
int n;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
int arr[10];
stand(time(0)); for(int
i=0;i<n;i++)
{
arr[i]=rand()%100;
lOMoARc PSD|28104798
lOMoARc PSD|28104798

}
printf(“Original array:\n”);
for(int i=0;i<n;i++)
{
printf(“%d”,arr[i]);
}
clock_t start=clock();
double time_taken=((double)(end-start))
printf(“\nSorted array:\n);
for(int i=0;i<n;i++)
{
printf(“%d”,arr[i]);
}
printf(“\nTime taken:%.2f ms\n”,time_taken);
return 0;
}
lOMoARc PSD|28104798

OUTPUT:

Enter the number of elements: 6

Original array:

60 56 27 20 77 9

Sorted array:

9 20 27 56 60 77

Time taken: 0.00 ms


lOMoARc PSD|28104798

RESULT:

Thus the quick sort to sort an array of element has been executedsuccessfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 10
N-QUEENS PROBLEM USING
DATE: BACKTRACKING

AIM:

To implement the program for N_QUEENS problem usingBacktracking

ALGORITHM:

1. Initialize an empty chessboard for size NxN

2. Start with the leftmost column and place a queen in the first row of thatcolumn

3. Move to the next column and place a queen in the first row of thatcolumn

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 therules of the problem

5. If all N queens have been places, print the solution

6. If it is not possible to place a queen in the current column withoutviolating the


rules of the problem, backtrack to the previous column

7. Remove the queen from the previous column and move it down onerow

8. Repeat steps 4-7 until all possible configurations have been tired
lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int board[20],count;
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)
{
if(board[i]==j)
printf(“\tQ”);
else
printf(“\t-“);
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++1)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==ans(i-row))
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{

if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
lOMoARc PSD|28104798
lOMoARc PSD|28104798

queen(row+1,n);
}
}
}
void main()
{
int n,i,j;
void queen(int row,int n);
printf(“Enter number of Queens:”);
scanf(“%d”,&n);
if(n<=3)
printf(“Number should be greater than 3”);
else
queen(1,n);
}
lOMoARc PSD|28104798

OUTPUT:

Enter number of Queens:3 Number


should be greater than 3 D:\siya>queens
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 - -
D:\siya
lOMoARc PSD|28104798

RESULT:

Thus the C program for N-Queens problem has been executed


lOMoARc PSD|28104798
lOMoARc PSD|28104798

EX.NO: 11
TRAVELLING SALESPERSON PROBLEM
DATE:

AIM:

To write an algorithm for Travelling Salesperson Problem

ALGORITHM:

1. Start the program

2. Declare the variables

3. Get input for the row elements

4. Find the shortest path

5. Find the minimum cost

6. Print the result

7. Stop the program


lOMoARc PSD|28104798
lOMoARc PSD|28104798

PROGRAM:

#include<stdio.h>
int matrix[25][25],visited_cities[10],limit,cost=0;int tsp(int c)
{
int count, nearest_city=999;
int minimum=999,temp;
for(count=0;count<limit;count++)
{
if((matrix[c][count]!=0)&&(visited_cities[count]==0))
{
if(matrix[c][count]<minimum)
{
minimum=matrix[count][0]+matrix[c][count];
}
temp=matrix[c][count];
nearest_city=count;
}
}
if(minimum!=999)
{
cost=cost+temp;
}
return nearest_city;
}
void minimum_cost(int city)
{
int nearest_city;
visited_cities[city]=1;
printf(“%d”,city+1);
nearest_city=tsp(city);
if(nearest_city==999)
{
nearest_city=0;
printf(“%d”,nearest_city+1);
cost=cost+matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}
int main()
{
int i,j;
printf(“Enter total number of cities:\t);
scanf(“%d”,&limit);
printf(“\nEnter Cost Matrix\n”);
for(i=0;i<limit;i++)
{
printf(“\nEnter %d elements in row[%d]\n”,limit,i+1);
for(j=0;j<limit,j++)
{
lOMoARc PSD|28104798
lOMoARc PSD|28104798

scanf(“%d”,&matrix[i][j]);
}
visited_cities[i]=0;
}
printf(“\nEnterted Cost Matrix:\n”);
for(i=0;i<limit;i++)
{
printf(“\n”);
for(j=0;j<limit;j++)
{
printf(“%d”,matrix[i][j]);
}
}
printf(“\n\nPath:\t”); minimum_cost(0);
printf(“\n\nMinimum Cost:\t”);
printf(“%d\n”,cost);
return 0;
lOMoARc PSD|28104798

OUTPUT:

Enter total number of cities: 4Enter

cost matrix

Enter 4 elements in row[1]

1 2 3 4

Enter 4 elements in row[2]

5 6 78

Enter 4 elements in row[3]

9 8 4 3

Enter Cost Matrix

1 2 3 4

5 6 7 8
3 4 5 6
9 8 4 3

Path: 1 4 3 2 1

Minimum Cost: 17
lOMoARc PSD|28104798

RESULT:

Thus the program was successfully executed


lOMoARcPSD|28104798
lOMoARcPSD|28104798

EX.NO: 12
IMPLEMENT RANDOMIZED ALGORITHMS FORFINDING
DATE: THE KTH SMALLEST NUMBER

AIM:
To implement randomized algorithms for finding kth smallest number

ALGORITHM:

1. Select a random element from a array as a pivot

2. Then partition to the array arount the pivot, its help to all the smaller elementwere placed before
in the pivot and all greater element are placed after the pivot

3. Then check the position of the pivot. If it is the kth element then return it

4. If it is the less than the kth element then repeat the process of the subarray

5. If it is the greater than the kth element then repeat the process of the leftsubarray
lOMoARcPSD|28104798
lOMoARcPSD|28104798

PROGRAM:

#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
int N=20;
int A[20];
void swap(int dex1, int dex2)
{
Int temp=A[dex1];
A[dex1]=A[dex2];
A[dex2]=temp;
}
int partition(int start,int end)
{
int i=start+1;
int j=I;
int pivot=start;
for(;i<end;i++)
{
if(A[i]<a[pivpt])
{
swap(i,j);
j++;
}
}
if(j<=end)
swap(pivot,(j-1));
return j=1;
}
void quick_sort(int start, int end, int K)
{
int part;
if(start<end)
{
part=partition(start,end);
if(part==K-1)
printf(“kth smallest element:%d”,A[part]);
if(part>K-1)
quick_sort(start, part, k);
}
return;
}
int main(int argc, char **argv)
{
int i;
time_t seconds; time(&seconds);
srand((unsigned int)seconds);
for(i=0;i<N;i++)
A[i]=rand()%(1000-1+1)+1;
printf(“The Original sequence is: “);
lOMoARcPSD|28104798
lOMoARcPSD|28104798

for(i=0;i<N;i++)
printf(“%d”,A[i]);
printf(“\nEnter the Kth smallest you want to find:”);
int k;
scanf(“%d”,&k);
quick_sort(0,N,k);
}
lOMoARcPSD|28104798

OUTPUT:

The original sequence is: 909 967 552 524 735 383 616 718 904 945 730 173
143 954 482 307 228 35 224 703

Enter the Kth smallest you want to find: 3Kth

smallest element: 173


lOMoARcPSD|28104798

RESULT:

Thus, to implement randomized algorithms for finding kth smallestnumber was


successfully executed.

You might also like