Algorithm Lab 115014
Algorithm Lab 115014
Name of the :
Register :
Semester :
ANNAI VEILANKANNI’S COLLEGE OF
ENGINEERING
Approved by AICTE-New Delhi & Affiliated to Anna University, Chennai
NO: 33, Gandhi Road, Nedungundrum, Chennai-127Tel: 044-22790022, 22790033,
2279004
BONAFIDE CERTIFICATE
Name :
Register no :
B.E/[Link]
PA
S.N DATE TIT MARK SIGN
G
O LE S
E
N
O
.
PA
S.N DATE TIT MARK SIGN
G
O LE S
E
N
O
.
PA
S.N DATE TIT MARK SIGN
G
O LE S
E
N
O
.
Ex. No. 1 Implementation of Linear Search
Date.
Aim :
Algorithm :
1. Start
5. Assign 0 to found
found = 1
Print "Element
Stop
7. If found = 0 then
8. Stop
Program :
#include <conio.h>
main()
found; clrscr();
for(i=0; i<n;i+
+) scanf("%d",
&a[i]);
found = 0;
for(i=0; i<n;
i++)
if (a[i] == val)
break;
if (found == 0)
getch();
}
Output :
23 6 12 5 0 32 10
5 Element found at
position 3
Result :
Ex. No. 2 Implementation of binary search Using Divide
Aim :
Algorithm :
1. Start.
ii) If x matches with the middle element, we return the mid index.
iii) Else If x is greater than the mid element, then x can only lie in
right half subarray after the mid element. So we traverse the
search in the right half.
7. stop.
Program :
#include <stdio.h>
if (r >= l)
// in left subarray
int main(void)
int n = sizeof(arr)/
array") else
result); return 0;
Output :
Result:
Ex. No. 3 Implementation of Naive algorithm for pattern
Matching Date.
Aim :
Algorithm :
1. Start.
5. pseudocode:
Algorithm-NAVE_STRING_MATCHING (T, P)
print "Match
Found" end
6. stop.
Program :
#include <stdio.h>
#include <string.h>
int M =
strlen(pat); int N
= strlen(txt);
i++) {
int j;
if (txt[i + j] !=
pat[j]) break;
if (j
// Driver's
code int
main()
call
search(pat,
txt);
return 0;
Output :
0 Pattern found at
at index 13
Result :
Ex. No.4 Implementation of Sorting - Insertion Sort
Date.
Aim :
Algorithm :
1. Start
5. Stop
Program :
#include
<stdio.h> void
main()
scanf("%d",&n);
scanf("%d",
&a[i]); for(i=1;
i<n; i++)
{
temp =
a[i]; j = i -
1;
a[j+1]
=a[j]; j = j
- 1;
a[j+1] =
temp; p++;
Output :
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64
Result :
Ex. No.5 Implementation of Sorting - Heap sort
Date.
Aim :
Algorithm :
1. Start.
2. First convert the array into heap data structure using heapify.
3. then one by one delete the root node of the Max-heap and replace it
with the last node in the
heap and then heapify the root of the heap. Repeat this process until the
size of the heap is greater than 1.
4. Repeat the following steps until the heap contains only one element:
i) Swap the root element of the heap (which is the largest element)
with the last element of the heap.
ii) Remove the last element of the heap (which is now in the correct
ii) At this point, the maximum element is stored at the root of the heap.
Replace it
with the last item of the heap followed by reducing the size of the
iii) Repeat step 2 while the size of the heap is greater than 1.
7. Stop.
Program :
#include <stdio.h>
*a = *b;
*b = temp;
// n is size of heap
// Initialize largest as
// left = 2*i + 1
int left = 2 * i
+ 1;
// right = 2*i + 2
int right = 2 * i
+ 2;
// so far
largest = right;
// If largest is not
root if (largest != i)
swap(&arr[i], &arr[largest]);
// sub-tree
heapify(arr, N, largest);
int N)
heapify(arr, N, i);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// root again
heapify(arr, i,
0);
printf("%d ",
arr[i]); printf("\n");
// Driver's
code int
main()
// Function call
heapSort(arr, N);
}
Output :
Sorted array
is
5,6,7,11,12,1
Result :
.
[Link].6 Implementation of Graph Traversal Using Breadth First Search
Date .
Aim :
Algorithm :
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: Enqueue all the neighbors of N that are in the ready state (whose
STATUS = 1) and set
their STATUS =
2 (waiting
state) [END OF
LOOP] Step 6:
EXIT
Program :
#include
<stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
// Constructor
Graph* Graph_create(int V)
Graph* g =
malloc(sizeof(Graph)); g->V =
V;
g->adj[i][j] = false;
return g;
// Destructor
visited[MAX_VERTICES]; for
visited[i] = false;
int
queue[MAX_VERTICES];
queue[rear++] = s;
print it s = queue[front++];
g->V;
adjacent++) {
visited[adjacent] = true;
queue[rear++] =
adjacent;
}
}
}
// Driver program to test methods of graph
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
Graph_destroy(g);
return 0;
Output :
vertex 2) 2 0 3 1
Result :
Ex. No.7 Implementation of Sorting- Merge Sort Uses Divide
Aim :
Algorithm :
1. Start
7. Stop
Program :
#include <stdio.h>
#include <conio.h>
void merge(int
int
size;
main()
int i, arr[30];
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted
+)
printf("%d
",arr[i]);
getch();
int i, mid;
if(min <
max)
max);
if (max-min == (size/2)-1)
", arr[i]);
int
tmp[30];
int i, j, k,
m; j =
min;
m = mid + 1;
{
if(arr[j] <= arr[m])
else
tmp[i] =
arr[j]; j++;
tmp[i] =
arr[m]; m+
+;
else
tmp[i] =
arr[k]; i++;
tmp[i] =
arr[k]; i++;
for(k=min; k<=max;
}
Output :
Result :
Ex. No. 8 Implementation of Prim’s Algorithm
Date.
Aim :
Algorithm :
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that
has minimum weight
Step 4: Add the selected edge and the vertex to the minimum spanning
Step 5: EXIT
Program :
#include<stdio.h
>
#include<conio.h
> int
a,b,u,v,n,i,j,ne=1;
int
visited[10]={0},min,mincost=0,cost[10]
scanf("%d",&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;
if(visited[u]==0 || visited[v]==0)
mincost+=min;
visited[b]=1;
cost[a][b]=cost[b][a]=999;
%d",mincost); getch();
}
Output :
Result :
Ex. No. 9 Implementation of Dijkstra’s
Algorithm Date.
Aim :
Algorithm :
Step 1. Start
Step 2. Obtain no. of vertices and adjacency matrix for the given graph
Step 3. Create cost matrix from adjacency matrix. C[i][j] is the cost of
Step 6. Create the distance matrix, by storing the cost of vertices from
vertex no. 0 to n-1
vertex
distance[i]=cost[0]
[i];
source. Step 8. Only, the vertices not marked as 1 in array visited[ ] should
if(visited[v]==0)
distance[v]=min(distanc
e[v] distance[w]
+cost[w][v]) Step 9.
Stop
Program :
/* Dijkstra’s Shortest
Path */ #include
<stdio.h>
#include <conio.h>
#define INFINITY
9999
#define MAX 10
cost[i][j] =
INFINITY; else
cost[i][j] = G[i][j];
distance[i] = cost[startnode][i];pred[i] =
startnode; visited[i] = 0;
distance[startnode] = 0;
visited[startnode] = 1;
{
mindistance =
i++)
mindistance = distance[i];nextnode=i;
visited[nextnode]
= 1; for(i=0; i<n;
i++) if(!visited[i])
count++;
for(i=0; i<n;
i++) if(i !=
startnode)
do
} while(j != startnode);
}
Output :
matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 0 60 0
= 2<-3<-0 Distance to
Distance to node4
= 60 Path = 4<-2<-3<-0
Result :
[Link].10 Implementation of Graph Traversal Using Depth First
Search Date.
Aim :
Algorithm:
Step 2: Push the starting node A on the stack and set its STATUS = 2
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbors of N that are in the ready state
(whose STATUS = 1) and set their STATUS = 2 (waiting state)
[END OF
LOOP] Step 6:
EXIT
Program :
#include <stdio.h>
#include <stdlib.h>
// Adjacency matrix
struct Graph {
int
V;
int
E;
int** Adj;
};
malloc(sizeof(struct Graph));
if (!G) {
printf(
"Mem
} ory
Error\
n");
return
NULL;
G->V = 7;
G->E = 7;
G->Adj = (int**)malloc((G->V) *
k++) {
v++) { G->Adj[u]
[v] = 0;
}
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 1;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 1;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 1;
G->Adj[6][2] = G->Adj[2][6] = 1;
return G;
vis[u] = 1;
printf("%d ",
u);
i++) { vis[i] =
0;
i++) { if (!vis[i]) {
DFS(G, i);
}
// Driver
code void
main()
struct Graph*
G; G =
adjMatrix();
DFStraversal(G
);
Output :
0134562
Result :
[Link]. 11 Implementation of Sorting - Quick Sort
Date.
Aim :
Algorithm :
quickSort(array, leftmostIndex,
rightmostIndex)
rightmostIndex)
partition(array, leftmostIndex,
pivotIndex
pivotElement
element[storeIndex] storeIndex++
Program :
#include <stdio.h>
// Function to swap
*b = temp;
//Partition Function
{
i
int j; t
i
n i
i (
v l
o o
t w
= -
a 1
r )
r ;
h for (j =
i l
g o
h w
] ;
;
j f
< (
= a
h r
i [
g j
h ]
- <
; p
j v
+ o
+ t
) )
{ {
i++;
i swap(&arr[i], &arr[j]);
swap(&arr[i + 1],
&arr[high]); return (i +
1);
// pi = Partition index
quicksort(Arr, low, pi -
1); quicksort(Arr, pi +
1, high);
}
// Main
Function int
main()
int size = 5;
int i;
printf("%d ",array[i]);
Output:
6 7 9 11 16
Result :
Ex .No: 12 Implementation of N Queens Problem
Date.
Aim:
Algorithm:
step 1 : Place the queens column wise, start from the left most
current column.
step 4 : Check if queen can be placed here safely if yes mark the current
cell in solution matrix as 1 and try to solve the rest of the problem
recursively.
step 5 : If placing the queen in the above step leads to the solution return true.
step 6 : If placing the queen in the above step does not lead to the
solution , BACKTRACK, mark the current cell in the solution matrix as 0 and
return false.
step 7 : If all the rows are tried and nothing worked, return false and print
NO SOLUTION.
Program :
using backtracking */
#define N 4
#include
<stdbool.h>
#include <stdio.h>
{
for (int i = 0; i < N; i++) {
printf("\n");
int i, j;
+)
if (board[row][i])
return false;
return false;
return false;
return true;
if (col >= N)
return true;
by one */
board[i][col] */
if (isSafe(board, i, col)) {
[col] */ board[i][col] = 1;
queens */ if (solveNQUtil(board,
col + 1))
return true;
solution, then
[col] */ board[i][col] = 0; //
BACKTRACK
}
/* If the queen cannot be placed in any row
*/
return false;
bool solveNQ()
{
int board[N][N] = { { 0, 0,
0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false)
printSolution(board
); return true;
solveNQ();
return 0;
}
Output:
..Q.
Q...
...Q
.Q..
Result :
[Link].13 Implementation of Floyd Algorithm
Date.
Aim:
Algorithm:
step 4 : If both pointers meet at some point then a loop exists and if the
Program :
include<stdio.h>
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(a[i][j]>a[i][k]+a[k][j])
a[i][j]=a[i][k]+a[k][j];
}
printf("All Pairs Shortest Path is :\
for(int j=0;j<n;j++)
printf("%d ",a[i][j]);
}
int main()
{
printf("\n");
}
}
int cost[4][4] = {{0, 3, 999, 4}, {8, 0, 2, 999}, {5, 999, 0, 1}, {2, 999, 999,
0}};
int n = 4;
floyd(cost,n);
Output
0354
5023
3601
2570
Result :
[Link]. 14 Implementation of Warshall Algorithm
Date.
Aim:
Algorithm :
step 1 : Initialize the solution matrix same as the input graph matrix as a first step.
step 3 : The idea is to one by one pick all vertices and updates all shortest
paths which include
step 5 : For every pair (i, j) of the source and destination vertices
respectively, there are two
possible cases.
of dist[i][j] as it is.
#include<stdio.
h>
#include<conio.
h>
#include<math.
h> int
max(int,int);
n) { int i,j,k;
for
(k=1;k<=n;k+
+) for
(i=1;i<=n;i++)
[j]=max(p[i][j],p[i][k]&&p[k][j]);
if(a>b)
return(a);
else
return(b);
void main() {
int p[10]
[10]=
{0
}
,n,e,u,v,i,
j; clrscr();
vertices:"); scanf("%d",&n);
for
(i=1;i<=e;i++)
scanf("%d%d",&u,&v);
p[u][v]=1;
for (j=1;j<=n;j++)
printf("%d\t",p[i]
[j]);
printf("\n");
warshal(p,n);
for (j=1;j<=n;j++)
printf("%d\t",p[i]
[j]);
printf("\n");
getch();
}
Output :
number of edges:5
0 1 1 0
0 0 1 0
0 0 0 1
1 0 0 0
Transitive closure:
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Result :
[Link] : 15 Implementation of Maximum and Minimum
Date.
Aim :
Algorithm :
step 2 : Recursively find the maximum and minimum of left part by calling
the same function i.e. leftMinMax[2] = minMax(X, l, mid)
step 3 : Recursively find the maximum and minimum for right part by
calling the same function i.e. rightMinMax[2] = minMax(X, mid + 1, r)
step 4 : Finally, get the overall maximum and minimum by comparing the
min and max of both halves.
Program :
minMax() */ #include<stdio.h>
struct pair
int
min;
int
max;
};
struct pair
minmax; int i;
max both*/ if (n == 1)
{
[Link] =
arr[0]; [Link]
= arr[0]; return
minmax;
{
r
[
}
0
else
]
{
;
} m
m i
i n
n m
m a
a x
x .
. m
m i
a n
a r
r 1
[ ]
1 ;
; m
m a
i x
n .
m m
a i
x n
m =
x a
= r
a 0
r ]
r ;
if (arr[i] >
[Link])
[Link] =
arr[i];
[Link] = arr[i];
return minmax;
}
/* Driver program to test above
int arr_size = 6;
Output :
Minimum element is 1
Maximum element is
3000
Result :
[Link].16 Implementation of Traveling salesman
problem Date.
Aim :
Algorithm :
step 2 : Repeat until all the nodes are visited : go to the nearest city(The
unvisited one) each time.
Program :
#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
int i,j;
scanf("%d",&n);
completed[i]=0;
printf("\n");
printf("\t%d",ary[i]
[j]);
int i,ncity;
completed[city]=1;
printf("%d---
>",city+1);
ncity=least(city);
if(ncity==999)
ncity=0;
printf("%d",ncity+1);
cost+=ary[city]
[ncity];
return;
mincost(ncity);
int least(int c)
int i,nc=999;
int min=999,kmin;
if((ary[c][i]!=0)&&(completed[i]==0))
min=ary[i][0]+ary[c]
[i]; kmin=ary[c][i];
nc=i;
if(min!
=999)
cost+=kmi
n; return
nc;
int main()
takeInput(); printf("\n\
",cost);
return 0;
Output :
Matrix
Enter Elements of
Row: 1 0 4 1 3
Enter Elements of
Row: 2 4 0 2 1
Enter Elements of
Row: 3 1 2 0 5
Enter Elements of
Row: 4 3 1 5 0
0413
4021
1205
3150
1—>3—>2—>4—>1
Minimum cost is 7
Result :
[Link].17 Implementation of Randomized Algorithms
Date.
Aim :
Algorithm :
step 2 : During quick sort, select a pivot element randomly from the range
of the array from low to high and move it to its correct position.
step 4 : Else if the index of pivot is greater than k, then scan for the left
subarray recursively, else scan for the right subarray recursively.
step 5 : Repeat this process until the element at index is not found
Program :
#include <stdlib.h>
{
// Sort the given array
// Driver's
code int
main()
// Function call
eleme
nt is
%d",
} kthSm
allest(
Output: arr, N,
printf("K'th K));
smalle return 0;
st
Result :