Algorithm Lab Manual
Algorithm Lab Manual
2OBJECTIVES:
Tounderstandandapplythealgorithmanalysistechniquesonsearchingandsortingalgorithms
Tocriticallyanalyzetheefficiencyof graphalgorithms
Tounderstanddifferentalgorithmdesigntechniques
Tosolveprogrammingproblemsusingstatespacetree
TounderstandtheconceptsbehindNPCompleteness,Approximationalgorithmsandrandomizedalgorit
hms.
LISTOFEXPERIMENTS
Searching andSortingAlgorithms
1. Implement Linear Search. Determine the time required to search for an element. Repeat
theexperimentfordifferentvaluesofn,thenumberofelementsinthelisttobesearchedandplotagraphofthe
timetakenversusn.
2. Implement recursive Binary Search. Determine the time required to search an element. Repeatthe
experiment for different values of n, the number of elements in the list to be searched andplot
agraph ofthetimetakenversusn.
3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ], char
txt[])thatprintsall occurrences ofpat[]intxt[].You mayassumethatn>m.
4. Sort a given set of elements using the Insertion sort and Heap sort methods and determine thetime
required to sort the elements. Repeat the experiment for different values of n, the
numberofelementsin thelisttobe sorted andplotagraph ofthetimetaken versusn.
GraphAlgorithms
1. DevelopaprogramtoimplementgraphtraversalusingBreadthFirst Search
2. DevelopaprogramtoimplementgraphtraversalusingDepth FirstSearch
3. Fromagivenvertexinaweightedconnectedgraph,developaprogramtofindtheshortestpathstootherverti
ces usingDijkstra’salgorithm.
4. FindtheminimumcostspanningtreeofagivenundirectedgraphusingPrim’salgorithm.
5. ImplementFloyd’salgorithmfortheAll-Pairs-Shortest-Pathsproblem.
6. Computethetransitiveclosureofagiven directedgraphusingWarshall'salgorithm.
AlgorithmDesignTechniques
1. Develop a program to find out the maximum and minimum numbers in a given list of n
numbersusingthe divide and conquer technique.
2. Implement Merge sort and Quick sort methods to sort an array of elements and determine
thetimerequiredtosort.Repeattheexperimentfordifferentvaluesofn,thenumberofelementsinthe
listtobe sortedandplotagraph ofthetimetakenversusn.
State SpaceSearchAlgorithms
1. ImplementNQueensproblemusingBacktracking.
ApproximationAlgorithmsRandomizedAlgorithms
1. Implement any scheme to find the optimal solution for the Traveling Salesperson
COURSE OUTCOMES: At the end of this course, the students will be able to:
CO1: Analyze the efficiency of algorithms using various frameworks
CO2: Apply graph algorithms to solve problems and analyze their efficiency.
CO3: Make use of algorithm design techniques like divide and conquer, dynamic programming, and greedy
techniques to solve problems
CO4: Use the state space tree method for solving problems.
CO5: Solve problems using approximation algorithms and randomized algorithms
COs–POsMAPPING:
SNO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 2 2 2 - 3 2 - 2 2 2 - 1 2 2 2
CO2 2 2 2 - 3 2 - 2 2 2 - 1 2 2 2
CO3 3 3 3 - 3 2 - 2 2 2 - 1 2 2 2
CO4 3 3 3 - 3 2 - 2 2 2 - 1 2 2 2
CO5 2 2 2 - 3 2 - 2 2 2 - 1 2 2 2
Aim:-ProgramtoimplementLinearSearch
Objective:TowriteaCprogramtoperformLinearSearch.
Theory: A max (min) heap is a complete binary tree with the property that the value
ateachnodeis atleastaslargeas(assmallas)thevaluesat
itschildren(iftheyexist)Callthispropertytheheapproperty.
Algorithm:
1
CS3401 ALGORITHM LABORATORY
/*ProgramforLinearSearch*/
#include<stdio.h>
intsearch(intarr[],intN,intx)
{
int i;
for (i = 0; i< N; i+
+)if(arr[i]==x)
return
i;return-1;
}
// Driver's
codeintmain(voi
d)
{
intarr[]={ 2, 3,4,10,40};
intx= 10;
intN =sizeof(arr)/ sizeof(arr[0]);
//Functioncall
int result = search(arr, N, x);
(result==-1)
?printf("Elementis notpresentinarray")
: printf("Element is present at index %d",
result);return0;
}
Output:
Conclusion:HencewehavestudiedandexecutedtheprogramforLinearsearch.
2
CS3401 ALGORITHM LABORATORY
DATE: BINARY SEARCH RECURSIVE
EXPT.NO:02
Aim:-ProgramtoimplementBinarySearchusingRecursive
Objective:TowriteaCprogramto performBinarySearchusingRecursive.
Theory: Binary Search is a search algorithm that is used to find the position of
anelement(targetvalue)in asorted array.Thearrayshouldbesorted priorto applying abinary
search.
Algorithm:
Step1:
Findthemiddleelementofarray.Using,middle=initial_v
alue+end_value /2 ;
Step2:Ifmiddle=element,return‘elementfound’andindex.
Step 3: if middle > element, call the function with end_value = middle -
1 .Step4:ifmiddle<element,callthefunctionwith start_value=middle+1 .Step
5:exit.
/*ProgramforBinarySearchusingRecursive*/
#include<stdio.h>
//Arecursivebinarysearchfunction.Itreturnslocationofxin
// given array arr[l..r] is present, otherwise -
1int binarySearch(int arr[],int l,int r,intx)
{
if (r>= l)
{
int mid=l+(r-l)/2;
//
Iftheelementispresentatthemiddleitselfif(arr[
mid] ==x) returnmid;
//Ifelement issmallerthan mid,thenitcanonlybepresent
//inleft subarray
if(arr[mid] >x) returnbinarySearch(arr,l,mid-1,x);
//
3
CS3401 ALGORITHM LABORATORY
Elsetheelementcanonlybepresentinrightsubarrayreturnbina
rySearch(arr,mid+1,r,x);
}
//Wereachherewhen elementisnot presentin
arrayreturn -1;
}
intmain(void)
{
int arr[]={2,3,4,10,40};
int n = sizeof(arr)/
sizeof(arr[0]);int x =10;
intresult =binarySearch(arr,0,n-1,x);
(result==-1)?printf("Element isnotpresentin array")
: printf("Element is present at index %d",
result);return0;
}}
Output:
Conclusion:HencewehavestudiedandexecutedtheprogramforBinarySearch usingRecursive.
4
CS3401 ALGORITHM LABORATORY
DATE: PATTERN MATCHING
EXPT.NO:03
Aim:-Programto implementPatternMatching
Objective:TowriteaCprogramto performPatternMatching.
Algorithm:
Start
pat_len := pattern
Sizestr_len:=string
size
for i := 0 to (str_len - pat_len),
doforj := 0topat_len,do
if text[i+j] ≠ pattern[j],
thenbreak
ifj==patLen,then
display the position i, as there pattern
foundEnd
/*ProgramforBinarySearchusingRecursive*/
#include<stdio.h>
#include<string.h>
intmain(){
char txt[] = "tutorialsPointisthebestplatformforprogrammers";char
pat[]= "a";
int M = strlen
(pat);intN=strlen(txt)
;
for (int i = 0; i<= N - M; i++)
{intj;
for (j = 0; j < M; j+
+)if(txt[i+j]!=pat[j])
5
CS3401 ALGORITHM LABORATORY
break;
if(j==M)
printf ("Pattern matches at index %d",i);
}
return 0;
}
Time complexities: - The time complexity of the Naive Algorithm is O(mn), where m
isthesize ofthe patterntobe searched andnisthesize ofthe containerstring.
Conclusion:HencewehavestudiedandexecutedtheprogramforPatternMatching.
6
CS3401 ALGORITHM LABORATORY
DATE: INSERTION SORT
EXPT.NO:4A
Aim:-ProgramtoimplementInsertionsort
Objective:TowriteaCprogramto performInsertionsort.
Theory: Insertion sort is a simple sorting algorithm that works similar to the
wayyousortplaying cardsinyourhands.Thearrayisvirtuallysplitintoasortedandan unsorted
part. Values from the unsorted part are picked and placed at thecorrectpositionin the
sortedpart.
Algorithm:
Start
pat_len := pattern
Sizestr_len:=string
size
for i := 0 to (str_len - pat_len),
doforj := 0topat_len,do
if text[i+j] ≠ pattern[j],
thenbreak
ifj==patLen,then
display the position i, as there pattern
foundEnd
/*ProgramforInsertionsort*/
/*Functiontosortanarrayusinginsertionsort*/
voidinsertionSort(int arr[],int n)
{
int i, key,j;
for (i = 1; i< n; i++)
{key= arr[i];
j= i-1;
7
CS3401 ALGORITHM LABORATORY
/* Move elements of arr[0..i-1], that
aregreater than key, to one position
aheadoftheir currentposition */
while (j >= 0 &&arr[j] > key)
{arr[j+ 1]=arr[j];
j =j -1;
}
arr[j+1]= key;
}
}
/*Driverprogramto
testinsertionsort*/intmain()
{
int arr[] ={12,11,13,5,6};
intn=sizeof(arr)/sizeof(arr[0]);
insertionSort(arr,n);pr
intArray(arr,n);
return0;
}
Output:
5 6 11 12 13
8
CS3401 ALGORITHM LABORATORY
Conclusion:HencewehavestudiedandexecutedtheprogramforInsertionsort.
Aim:-ProgramtoimplementHeapsort.
Objective:TowriteaCprogramto performHeapsort.
Theory: Heap sort is a comparison-based sorting algorithm that utilizes the concept of a
binary heap. It divides the input array into two parts: a sorted region and an unsorted
region. The algorithm repeatedly extracts the maximum (for ascending order) or
minimum (for descending order) element from the unsorted region and places it at the
end of the sorted region.
Algorithm:
Step1:Starttheprocess.Step2:
Declarethevariables.
Step3:Enterthelistofelements tobesortedusingthegetfunction.
Step4:Divide thearraylist intotwo halvesthelower arraylistand
upperarraylistusingthemergesortfunction.
Step5:Sortthetwoarraylist.
Step6:Combinethetwosortedarrays.
Step7:Displaythesortedelementsusingtheget()function.Step8:
Stoptheprocess
/*ProgramforHeapsort*/
#include<stdio.h>
void
heapsort(int[],int);voidh
eapify(int[],int);
voidadjust(int[],int);voi
dmain()
{
9
CS3401 ALGORITHM LABORATORY
int
n,i,a[50];c
lrscr();
printf("\
nEnterthelimit:");scanf
("%d",&n);
printf("\
nEntertheelements:");for(i=0
;i<n;i++)
scanf("%d",&a[i]);heapsort(
a,n);
printf("\nThe Sorted Elements Are:\
n");for(i=0;i<n;i++)
printf("\n
%d",a[i]);printf("\
n");
getch();
}
void heapsort(int a[],int n)
{inti,t;
heapify(a,n);
for(i=n-1;i>0;i--){
t=
a[0];a[0]
=a[i];a[i]
=t;
adjust(a,i);
}
}
void heapify(int a[],int n)
{intk,i,j,item;
for(k=1;k<n;k++){
item=a[k];i
=k;
j=
(i-1)/2;while((i>0)&&(item>a[
j])){
a[i]= a[j];i
10
CS3401 ALGORITHM LABORATORY
=j;
j=(i-1)/2;
}
a[i]=item;
}
}
voidadjust(inta[],intn)
{inti,j,item;
j =0;
item=a[j];i
=2*j+1;
while(i<=n-1){
if(i+1 <= n-
1)if(a[i]<a[i
+1])i++;
if(item<a[i]){
a[j]= a[i];j
=i;
i=2*j+1;
}else
break;
}
a[j]=item;
}
Output:
32
45
54
67
87
90
Time complexities: - Though the call of Heapify requires only O(n) operations,
Adjustpossibly requires O(log n) operations for each invocation. Thus the worst case time
isO(nlog n).
12
CS3401 ALGORITHM LABORATORY
DATE: GRAPH TRAVERSAL BREADTH FIRST SEARCH
EXPT.NO:5
Aim:-ProgramtoimplementgraphtraversalusingBreadthFirstSearch.
Objective:WriteaCprogramtoimplementgraphtraversalusingBreadthFirstSearch.
Theory:
BFS Breadth First Search is an algorithm used to search the Tree or Graph. BFS search
starts from rootnode then traversal into next level of graph or tree and continues, if item
found it stops otherwise itcontinues.ThedisadvantageofBFS
isitrequiresmorememorycomparetoDepthFirstSearch(DFS).
Algorithm:
13
CS3401 ALGORITHM LABORATORY
//ProgramforgraphtraversalusingBFS//
#include<stdio.h>
#include<conio.h>
inta[20][20],q[20],visited[20],n,i,j,f=0,r=-
1;voidbfs(intv){
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++]);
}
}
voidmain(){
int
v;clrscr
();
printf("\
nEnterthenumberofvertices:");scanf("%d
",&n);
for(i=1;i<=n;i++){
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\
n");for(i=1;i<=n;i++)
for (j=1;j<=n;j+
+)scanf("%d",&a[i]
[j]);
printf("\
nEnterthestartingvertex:");scanf("%d
",&v);
bfs(v);
printf("\n The node which are reachable are:\
n");for(i=1;i<=n;i++)
if(visited[i])printf("%
d\t",i);else
printf("\
nBfsisnotpossible");getch();
}
14
CS3401 ALGORITHM LABORATORY
Output:
0100
1100
0101
1001
Time Complexities:-Let T(n,e) and S(n,e) be the maximum time and maximum
additional space takenby algorithm BFS on any graph G with n vertices and e edges. T(n,
e) = Θ(n + e) and S(n, e) = Θ(n) if Gis represented by its adjacency lists. If G is
represented by its adjacency matrix, then T(n, e) =Θ(n²) andS(n,e)=Θ(n).
Conclusion:-ThustheCprogramforgraphtraversal
usingbreadthfirstsearchhasexecutedsuccessfully.
15
CS3401 ALGORITHM LABORATORY
DATE: GRAPH TRAVERSALDEPTH FIRST SEARCH
EXPT.NO:6
Objective:-WriteaCprogramtoimplementgraphtraversalusingDepthFirstSearch.
Theory:-DFS Depth First Search is an algorithm used to search the Tree or Graph.
DFSsearch startsfrom root node then traversal into left child node and continues, if
item found it stops otherwise
itcontinues.TheadvantageofDFSisitrequireslessmemorycomparetoBreadthFirstSearch(
BFS).
Algorithm:-
//ProgramforgraphtraversalusingDepth
FirstSearch//#include<stdio.h>
#include<conio.h>
int a[20]
[20],reach[20],n;voiddfs(intv)
{
int
i;reach[v]=
1;
for (i=1;i<=n;i++) if(a[v]
[i]&&!reach[i]){
16
CS3401 ALGORITHM LABORATORY
printf("\n%d->
%d",v,i);dfs(i);
}
17
CS3401 ALGORITHM LABORATORY
}
voidmain(){
int
i,j,count=0;clr
scr();
printf("\
nEnternumberofvertices:");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);print
f("\n");
for(i=1;i<=n;i++){
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
elseprintf("\
nGraphisnotconnected"); getch();
18
CS3401 ALGORITHM LABORATORY
OUTPUT:
Enter number of vertices: 4
0111
1001
1001
1110
1->2
2->4
4->3
Graph is connected
TimeComplexities:-LetT(n,e)andS(n,e)bethemaximumtimeandmaximum-
additionalspacetaken byalgorithmDFSforan n-vertexande-edgegraph, thenS(n,e)
=Θ(n)andT(n,e)=Θ(n+e)ifadjacencylistsareusedandT(n,e)=Θ(n²)ifadjacencymatrices
areused.
Conclusion:-
ThustheCprogramforgraphtraversalusingdepthfirstsearchhasexecutedsuccessfully.
19
CS3401 ALGORITHM LABORATORY
DATE: DIJKSTRA’S ALGORITHM
EXPT.NO:7
Aim:-ProgramtoimplementDijkstra’sAlgorithm
Objective:TowriteaCprogramtoperformDijkstra’sAlgorithm.
Theory:Dijkstra'salgorithmallowsustofindtheshortestpathbetweenanytwoverticesof a
graph. It differs from the minimum spanning tree because the shortest
distancebetweentwoverticesmightnotinclude alltheverticesofthegraph
Algorithm:
Markthesourcenodewithacurrentdistanceof0andtherestwithinfinity.
1. Setthenon-visitednodewiththesmallestcurrentdistanceasthecurrentnode,letssayC.
2. For each neighbour N of the current node C: add the current distance of C with
theweight of the edge connecting C-N. If it is smaller than the current distance of
N,setitasthenewcurrentdistance of N.
3. Markthecurrentnode Cas visited.
4. Gotostep2 ifthereareany nodes areunvisited.
/*ProgramforDijkstra’sAlgorithm*/
//CprogramforDijkstra's singlesourceshortestpath
//algorithm.Theprogramisforadjacencymatrix
//representationofthegraph
#include
<limits.h>#include<stdbo
ol.h>#include<stdio.h>
20
CS3401 ALGORITHM LABORATORY
int min = INT_MAX, min_index;for (int
v= 0;v<V;v++)
returnmin_index;
}
//FunctionthatimplementsDijkstra'ssinglesource
//shortestpathalgorithmforagraphrepresentedusing
// adjacency matrix
representationvoiddijkstra(intgraph[V]
[V],intsrc)
{
intdist[V];// Theoutputarray.dist[i]willholdthe
//shortest
// distancefromsrctoi
//Initializeall distancesasINFINITEandstpSet[]as
//false
for (int i= 0;i<V; i++)
dist[i]=INT_MAX,sptSet[i]=false;
//Findshortestpathforall vertices
for(int count=0; count< V -1; count++){
21
CS3401 ALGORITHM LABORATORY
//Picktheminimumdistancevertex fromtheset of
//Updatedist[v]onlyifis notinspite,
//Thereisanedgefromutov,andtotal
// weightofpath fromsrctov throughuis
// smaller than current value of dist[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];
}
//
printtheconstructeddistancearrayprintSolution(
dist);
}
// driver's
codeintmain()
{
/*Letuscreatetheexamplegraphdiscussedabove*/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}};
// Function
calldijkstra(graph,0);
return0;
}
22
CS3401 ALGORITHM LABORATORY
Output:
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Conclusion:
HencewehavestudiedandexecutedtheprogramforDijkstra’sAlgorithm.
23
CS3401 ALGORITHM LABORATORY
DATE: PRIM’S ALGORITHM
EXPT.NO:8
Aim:-Programtoimplementprim’salgorithmusingthe greedymethod
Objective:WriteaCprogramtofindtheminimumspanningtreetoimplementprim’salgorith
musinggreedymethod
Algorithm:
//CProgramtoimplementprim’salgorithmusinggreedymethod
#include<stdio.h>
#include<conio.h>
intcost[10][10];
24
CS3401 ALGORITHM LABORATORY
25
CS3401 ALGORITHM LABORATORY
voidprim(){
inti,j,startVertex,endVertex;
int k,nr[10],temp,minimumCost=0,tree[10][3];
/*Forfirst smallestedge*/temp
=cost[0][0];
for (i = 0; i< n; i++)
{ for(j=0;j <n;j++){
if(temp>cost[i][j]){
temp=cost[i]
[j];startVertex =
i;endVertex=j;
}
}
}
/*Nowwehavefistsmallestedgeingraph*/
tree[0][0]=startVertex;
tree[0]
[1]=endVertex;tree[0]
[2] =
temp;minimumCost=te
mp;
for(i=0;i<n; i++) {
if(cost[i][startVertex]<cost[i]
[endVertex])nr[i]=startVertex;
else
nr[i]=endVertex;
}
26
CS3401 ALGORITHM LABORATORY
if(nr[j]!=100 &&cost[j][nr[j]]<temp)
{temp=cost[j][nr[j]];
k=j;
}
}
/*Nowihavegotnextvertex*/
tree[i][0]=k;
tree[i][1]=nr[k];tree[i]
[2]=cost[k][nr[k]];
minimumCost=minimumCost+cost[k][nr[k]];nr[k]
=100;
for(j=0;j<n;j++){
if(nr[j]!=100&&cost[j][nr[j]] >cost[j][k])nr[j]
=k;
}
temp=99;
}
printf("\
nTheminspanningtreeis:-");for(i =0;
i<n -1;i++){
for (j = 0; j < 3; j+
+)printf("%d",tree[i]
[j]);
printf("\n");
}
printf("\nMincost:%d",minimumCost);
}
voidmain()
{int i,
j;clrscr();
printf("\
nEntertheno.ofvertices:");scanf("%d
",&n);
printf("\nEnterthe costsofedgesinmatrixform:");
27
CS3401 ALGORITHM LABORATORY
for(i=0;i<n;i+
+)for(j=0;j <n;j++){
scanf("%d",&cost[i][j]);
}
printf("\nThe matrix is :
");for(i=0;i<n; i++) {
for (j = 0; j < n; j++)
{printf("%d\t",cost[i]
[j]);
}
printf("\n");
}
prim();
getch();
}
28
CS3401 ALGORITHM LABORATORY
Output:
4567
1234
4567
5889
Min cost: 10
Conclusion:-ThustheCprogramtofind
theminimumspanningtreeusingprim’salgorithmhasexecutedsuccessfully.
29
CS3401 ALGORITHM LABORATORY
DATE: ALL PAIR SHORTEST PATH
EXPT.NO:9
Objective:-WriteaCprogramtofindall pairsshortestpathusingFloyd’salgorithm.
Algorithm:-
AlgorithmFloyd(W[1..n,1..n])
//ImplementsFloyd’salgorithmfortheall-pairsshortestpathsproblem
//Input:Theweight matrix Wofagraph
//Output:Thedistancematrixofshortestpathslength
{
D← W
fork←1to ndo
{
fori← 1to ndo
{
forj← 1to ndo
{
D[i,j]←min(D[i,j],D[i,k]+D[k,j])
}
}
}
returnD
}
30
CS3401 ALGORITHM LABORATORY
//AllpairsShortestpath //
Program:#incl
ude<stdio.h>#incl
ude<conio.h>
void floyd(int[10]
[10],int);intmin(int,int);
voidmain()
{
intn,a[10][10],i,j;
printf("Entertheno.ofnodes:");sc
anf("%d",&n);
printf("\nEnter the cost adjacency matrix\
n");for(i=1;i<=n;i++)
for(j=1;j<=n;j+
+)scanf("%d",&a[i]
[j]);floyd(a,n);getch();
}
voidfloyd(inta[10][10],intn)
{
int d[10]
[10],i,j,k;for(i=1;i
<=n;i++)
{
for(j=1;j<=n;j+
+)d[i][j]=a[i][j];
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
printf("\nThe distance matrix is\
n");for(i=1;i<=n;i++)
31
CS3401 ALGORITHM LABORATORY
{
for(j=1;j<=n;j++)
{
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
intmin(inta,intb)
{
if(a<b)ret
urn
a;elseretur
nb;
}
32
CS3401 ALGORITHM LABORATORY
Output:
999999999
999999999
999 1 999
Transitive closure:
0 999999
999 0 999
999 1 0
<1,2>=999
<1,3>=999
<2,1>=999
<2,3>=999
<3,1>=999
<3,2>=1
Complexity:-ThetimeefficiencyofFloyd’salgorithmiscubici.e.Θ(n3)
Conclusion:-
ThustheCprogramtofindshortestpathusingFloyd’salgorithmhasexecutedsuccessfully.
33
CS3401 ALGORITHM LABORATORY
DATE: WARSHELL ALGORITHMTRANSITIVE CLOSURE
EXPT.NO:10
Aim:-ProgramtoimplementWarshallAlgorithmusingtransitiveclosure
Objective:TowriteaCprogramtoperformWarshallAlgorithmusingtransitiveclosure.
Algorithm:
Step1:First,readthesearchelement (Targetelement)in thearray.
Step 2: In the second step compare the search element with the first element in the
array.Step 3: If both are matched, display “Target element is found” and terminate the
LinearSearch
function.
Step4:Ifbotharenotmatched,comparethesearchelementwiththenextelementinthearray.
Step5: Inthis step,repeatsteps3 and4 untilthesearch (Target)elementis comparedwiththe
lastelementofthearray.
Step6–Ifthelast elementin
thelistdoesnotmatch,theLinearSearchFunctionwillbeterminated,andthe message“Elementis
notfound”willbedisplayed.
/*ProgramforWarshallAlgorithmusingtransitiveclosure*/
#include<stdio.h>
#include<math.h>intm
ax(int,int);
void warshal(int p[10][10],int n) {int
i,j,k;
for (k=1;k<=n;k++)for
(i=1;i<=n;i+
+)for(j=1;j<=n;j++)
p[i][j]=max(p[i][j],p[i][k]&&p[k][j]);
}
intmax(inta,intb){
34
CS3401 ALGORITHM LABORATORY
if(a>b)return(a);el
se
return(b);
}
voidmain(){
int p[10][10]= {0
}
,n,e,u,v,i,j;
printf("\n Enter the number of
vertices:");scanf("%d",&n);
printf("\n Enter the number of
edges:");scanf("%d",&e);
for(i=1;i<=e;i++){
printf("\n Enter the end vertices of edge %d:",i);scanf("%d
%d",&u,&v);
p[u][v]=1;
}
printf("\n Matrix of input data: \
n");for(i=1;i<=n;i++) {
for (j=1;j<=n;j++)printf("%d\
t",p[i][j]);
printf("\n");
}
warshal(p,n);
printf("\n Transitive closure: \
n");for(i=1;i<=n;i++) {
for (j=1;j<=n;j++)printf("%d\
t",p[i][j]);
printf("\n");
}
}
35
CS3401 ALGORITHM LABORATORY
Output:
Time complexities: -Time complexity for Warshall Algorithm using transitive closure
isdenoted by O(n3) as everyelementinthearrayis compared onlyonce.
36
CS3401 ALGORITHM LABORATORY
DATE: MAXIMUM AND MINIMUM
EXPT.NO:11
Aim:-Programtofindoutmaximumandminimumusing divideandconquerrule.
37
CS3401 ALGORITHM LABORATORY
//Programtofindoutmaxandminusingdivideandconquerrule
#include<conio.h>#i
nclude<stdio.h>intm
ain()
{
int
i,j,a[100],max=0,min=1000,mid,n,max1,max2,min1,min2;pri
ntf("enterthe sizeof thearray");
scanf("%d",&n);
printf("entertheelementsofthearray");for
(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
j=n-
1;int
p=0;if(
p==j)
{
max=min=a[p];//
wenderisonlyoneelementinarrayprintf("maxis:
%dandminis :%d",max,min);
}
elseif(p==j-1)
{
if(a[p]<a[j])
{
max=a[j];
min=a[p];
}
else
{
max=a[p];
min=a[j];
}
printf("maxis:%dandminis:%d",max,min);
}
else
{
mid=(int)((p+j)/
2);for(i=0;i<mid;i
++)
38
CS3401 ALGORITHM LABORATORY
{
39
CS3401 ALGORITHM LABORATORY
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
max1=max;min1=
min;printf("\nmax1
is :%d\n",max1);
printf("\n is :%d\n",min1);
min1max=0;
min=1000;
for(i=mid;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
max2=max;
min2=min;
printf("\nmax2 is :%d\
n",max2);printf("\nmin2is:%d\
n",min2);
if(max1<max2)
{
max=max2;
}
else
max=max1;if(m
in1<min2)
{
min=min1;
40
CS3401 ALGORITHM LABORATORY
}
else
{
min=min2;
}
printf("\nmaximum is:%d\
n",max);printf("\nminimunis:%d\
n",min);
}
getch();retur
n0;
}
OUTPUT:
max1 is :198
min1 is :23
max2 is :90
min2 is :12
maximum is:198
minimum is:12
Conclusion:Thus,theProgramtofindoutmaximumandminimumusingdivideandconquer
rulehasbeen completed successfully.
41
CS3401 ALGORITHM LABORATORY
DATE: MERGE SORT
EXPT.NO:12A
Aim:-ProgramtoimplementMergeSort.
Theory: As another example of Divide and conquer a sorting algorithm that in the worst
case itscomplexity is O(n log n). This algorithm is called Merge Sort. Merge sort
describes this process usingrecursionandafunction Mergewhich merges twosortedsets.
Algorithm:
Mergesort isaperfect exampleof asuccessful application ofthe divide-and-conquertechnique.
1. Splitarray A[1..n]intwo andmakecopiesofeachhalfinarraysB[1.. n/2]andC[1..
n/2]
2. SortarraysBandC
3. MergesortedarraysBandCintoarray Aas follows:
a) Repeatthefollowinguntilnoelementsremaininoneofthearrays:
i. comparethefirstelementsintheremainingunprocessedportionsofthearrays
ii. copythesmallerofthetwointoA,whileincrementingtheindexindicatingtheunproce
ssedportionof thatarray
b) Onceallelementsinoneofthearraysareprocessed,copytheremainingunproc
essedelementsfromtheother arrayintoA.
//ProgramtoimplementmergesortusingDivideandconquer
#include<stdio.h>#include
<conio.h>inta[50];
voidmerge(int,int,int);
voidmerge_sort(intlow,inthigh)
{
int
mid;if(low<
high)
{
mid=(low+high)/
2;merge_sort(low,mid);
42
CS3401 ALGORITHM LABORATORY
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
voidmerge(intlow,intmid,int high)
{
int
h,i,j,b[50],k;h=l
ow;
i=low;j=
mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}i+
+;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
43
CS3401 ALGORITHM LABORATORY
for(k=low;k<=high;k++)a[k]=b[k];
}
intmain()
{
intnum,i;
printf("\t\t\tMERGE SORT\
n");printf("\nEnter the total
numbers: ");scanf("%d",&num);
printf("\nEnter%dnumbers:\
n",num);for(i=1;i<=num;i++)
{
scanf("%d",&a[i]);
}
merge_sort(1,num);printf("\
nSORTEDORDER:\n");
for(i=1;i<=num;i++) printf("\t
%d",a[i]);getch();
}
44
CS3401 ALGORITHM LABORATORY
OUTPUT:
MERGE SORT
Enter 6 numbers:
98 110 34 65 87 12
SORTED ORDER:
12 34 65 87 98 110
TimeComplexities:-
All cases have same efficiency: O( nlog
n),Spacerequirement:O(n )(NOTin-place)
45
CS3401 ALGORITHM LABORATORY
DATE: QUICK SORT
EXPT.NO:12B
Aim:-ProgramtoimplementQuicksort.
Theory: Quick Sort divides the array according to the value of elements. It rearranges
elements of agiven array A[0..n-1] to achieve its partition, where the elements before
position s are smaller than orequalto A[s]and alltheelements after positions
aregreaterthanorequal to A[s].
Algorithm:
Step1:Starttheprocess.Step2:
Declarethevariables.
Step3:Enterthelist ofelementsto besortedusingtheget()function.
Step4: Dividethearraylist intotwo halvesthelowerarray list andupper
arraylistusingthemergesortfunction.
Step5:Sortthetwoarraylist.
Step6:Combinethetwosortedarrays.Step7:Dis
playthesortedelements.
Step8:Stoptheprocess.
#include <stdio.h>
#include
<conio.h>voidqsort();
intn;
voidmain()
{
int
a[100],i,l,r;clr
scr();
printf("\nENTERTHESIZEOFTHEARRAY:");
scanf("%d",&n);
for(i=0;i<n;i++)
46
CS3401 ALGORITHM LABORATORY
{
printf("\nENTERNUMBER-%d:",i+1);
47
CS3401 ALGORITHM LABORATORY
scanf("%d",&a[i]);
}
printf("\nTHEARRAYELEMENTSBEFORESORTING:\n");
for(i=0;i<n;i++)
{
printf("%5d",a[i]);
}l=
0;
r=n-1;
qsort(a,l,r);
printf("\nTHEARRAYELEMENTSAFTERSORTING: \n");
for(i=0;i<n;i++)
printf("%5d",a[i]);
getch();
}
voidqsort(intb[],intleft,intright)
{
int
i,j,p,tmp,finished,k;if(r
ight>left)
{
i=left;j=rig
ht;p=b[left]
;finished=0
;
while(!finished)
{
do
{
++i;
}
while((b[i]<=p)&&(i<=right));
while((b[j]>=p)&&(j>left))
{
--j;
}
if(j<i)
finished=1;
else
{
tmp=b[i];
48
CS3401 ALGORITHM LABORATORY
b[i]=b[j];b[j]=tmp;
}
}
tmp=b[left];b[left]=b[j];
b[j]=tmp; qsort(b,left,j-
1);qsort(b,i,right);
}
return;
}
49
CS3401 ALGORITHM LABORATORY
Output:
ENTER THE SIZE OF THE ARRAY: 5
ENTER NUMBER-1: 12
ENTER NUMBER-2: 45
ENTER NUMBER-3: 67
ENTER NUMBER-4: 8
ENTER NUMBER-5: 77
Timecomplexities:-
QuicksorthasanaveragetimeofO(nlogn)onnelements.ItsworstcasetimeisO(n²).
50
CS3401 ALGORITHM LABORATORY
DATE: N QUEEN’S PROBLEM
EXPT.NO:13
Aim:-ProgramtoimplementNqueen’sproblem
Objective:-WriteaCprogramtosolveNqueen’sproblemusingBacktracking
Theory:-N Queen’s problem is the puzzle. Placing chess queens on a chessboard, so that
No twoqueensattack each other.Backtrackingis usedto solvetheproblem.
The n-queens problem consists of placing nqueens on an n x n checker board in such
away that they donot threaten each other, according to the rules of the game of
chess.Every queen on a checker squarecan reach the other squares that are located on the
same horizontal, vertical, and diagonal line. So therecan be at most one queen at
eachhorizontal line, at most one queen at each vertical line, and at most onequeen at each
of the 4n-2 diagonal lines. Furthermore, since we want to place as many queens
aspossible, namely exactly nqueens, there must be exactly one queen at each
horizontalline and at eachvertical line. The concept behind backtracking algorithm which
is used to solve this problem is tosuccessively place the queens in columns. When it is
impossible to place a queen in a column (it is onthe same diagonal, row, or column as
another token), the algorithm backtracks and adjusts a precedingqueen
Algorithm:-
51
CS3401 ALGORITHM LABORATORY
//CProgramforNqueen’sproblemusingBacktracking//
#include<stdio.h>#in
clude<conio.h>#incl
ude<math.h>inta[30
],count=0;intplace(i
ntpos){inti;
for(i=1;i<pos;i++){
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))return0;
}
return1;
}
voidprint_sol(intn)
{int
i,j;count++;
printf("\n\nSolution#%d:\
n",count);for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if(a[i]==j)printf("Q\
t");elseprintf("*\
t");
}
printf("\n");
}
}
voidqueen(intn){int
k=1;a[k]=0;
while(k!=0){
a[k]=a[k]
+1;while((a[k]<=n)&&!
place(k))
a[k]++;
if(a[k]<=n){
if(k==n)print_sol(n);
else{
k+
+;a[k]=
0;
}
52
CS3401 ALGORITHM LABORATORY
}
elsek--;
}
}
void main()
{inti,n;clrscr();
printf("Enter the number of Queens\
n");scanf("%d",&n);
queen(n);
printf("\nTotalsolutions=
%d",count);getch();
}
OUTPUT:
53
CS3401 ALGORITHM LABORATORY
Enter the number of Queens
4
Solution #1:
* Q * *
* * * Q
Q * * *
* * Q *
Solution #2:
* * Q *
Q * * *
* * * Q
* Q * *
Total solutions=2
Complexity:-
Thepowerofthesetofallpossiblesolutionsofthenqueen’sproblemisn!
andtheboundingfunctiontakesalinearamount oftimeto calculate,thereforetherunningtimeof
thenqueens problemis O(n!).
Conclusion:-ThustheCprogramtosolveN
queen’sproblemusingBacktrackinghasexecutedsuccessfully.
54
CS3401 ALGORITHM LABORATORY
DATE: APPROXIMATION ALGORITHM FORSALESMAN PROBLEM
EXPT.NO:14
Aim:-ProgramtoimplementApproximateAlgorithmusingTravellingSearchPerson.
Objective:TowriteaCprogramtoperformApproximateAlgorithmusingTravellingSearchPerson.
Theory: The traveling salesman problem (TSP) is NP-hard and one of the most well-
studied combinatorial optimization problems. It has broad applications in
logistics,planning,andDNAsequencing..
Algorithm:
1. Let1bethestartingandendingpointforsalesman.
2. ConstructMSTfromwith1asrootusingPrim’sAlgorithm.
3. ListverticesvisitedinpreorderwalkoftheconstructedMSTandadd1attheend.
/*ProgramforApproximateAlgorithmusingTravelling SearchPerson*/#include<stdio.h>
intary[10][10],completed[10],n,cost=0;
voidtakeInput()
{
int i,j;
printf("Enterthenumberofvillages:");scanf("%d",&
n);
<n;i++)
{
printf("\nEnterElementsofRow:%d\n",i+1);
completed[i]=0;
}
printf("\n\nThecostlistis:");
55
CS3401 ALGORITHM LABORATORY
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j <n;j++)printf("\t
%d",ary[i][j]);
}
}
voidmincost(intcity)
{
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);
}
intleast(intc)
{
inti,nc=999;
intmin=999,kmin;
for(i=0;i<n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c]<min)
{
min=ary[i][0]+ary[c][i];kmin=ary[c][i];
56
CS3401 ALGORITHM LABORATORY
nc=i;
}
}
if(min!
=999)cost+=k
min;
returnnc;
}
intmain()
{
takeInput();
printf("\n\nThePathis:\n");
mincost(0);//passing0becausestartingvertexprintf("\n\nMinimumcostis %d\n",cost);
return0;
}
57
CS3401 ALGORITHM LABORATORY
Timecomplexities:-
TimecomplexityforApproximateAlgorithmusingTravellingSearchPersonisdenotedbyO(n
2n)aseveryelement inthearrayiscomparedonlyonce.
Conclusion:HencewehavestudiedandexecutedtheprogramforApproximateAlgorithmusingT
ravellingSearchPerson.
58
CS3401 ALGORITHM LABORATORY
DATE: RANDOMIZED ALGORITH FOR KTH SMALLEST ELEMENT
EXPT.NO:15
Aim:-ProgramtoimplementRandomizedalgorithmforkthsmallestelement.
Objective:TowriteaCprogramtoperformRandomizedalgorithmforkthsmallestelement.
Algorithm:
1. Generateintegerfrom1to7withequalprobability.
2. Implementrandom-0-6-Generatorusingthegivenrandom-0-1-Generator.
3. Selectarandomnumberfromstream,withO(1)space.
4. Randomnumbergeneratorinarbitraryprobabilitydistributionfashion.
5. ReservoirSampling.
6. LinearityofExpectation.
/*ProgramforRandomizedalgorithmforkthsmallestelement*/
#include<stdio.h>
#include<stdlib.h>
//Comparefunctionforqsort
intcmpfunc(constvoid*a,constvoid*b)
{
return(*(int*)a-*(int*)b);
}
//FunctiontoreturnK'thsmallest
// elementin agivenarray
intkthSmallest(intarr[],intN,intK)
{
// Sort the givenarray
qsort(arr,N,sizeof(int),cmpfunc);
{
intarr[]={ 12,3,5,7,19};
intN =sizeof(arr)/sizeof(arr[0]),K =2;
//Functioncall
printf("K'th smallest element is
%d",kthSmallest(arr,N,K));
return0;
}
Output:
Timecomplexities:-
TimecomplexityforRandomizedalgorithmforkthsmallestelementisdenotedbyO(Nlog N)as
everyelement inthearrayis comparedonly once.
60
CS3401 ALGORITHM LABORATORY
DATE: KNAPSACK PROBLEM
EXPT.NO:16
Aim:-ProgramtoimplementKnapsackproblem
Objective:TowriteaCprogramtosolveknapsackproblemusingGreedymethod
Theory:
Algorithm:
Step1:Starttheprogram.
Step2:Declarethevariable.
Step3:Usingthegetfunctionreadthenumberofitems,capacityof the bag,Weightof theitemand
valueof theitems.
Step4:Findthesmallweight withhigh valueusing thefind
function.Step5:Findtheoptimalsolutionusingthefunctionfindop().
Step6: Display the optimal solution for the items.
Step7:Stopthe process
61
CS3401 ALGORITHM LABORATORY
62
CS3401 ALGORITHM LABORATORY
//ProgramtoimplementKnapsackproblemusingGreedymethod
#include<stdio.h>
voidknapsack(intn,floatweight[],floatprofit[],floatcapacity){floatx[20],tp
=0;
inti,j, u;
u=capacity;
for(i=0;i<n;i+
+)x[i]=0.0;
if(i<n)
x[i]=u /weight[i];
tp = tp + (x[i] * profit[i]);printf("\
nTheresultvectoris:-");for(i
=0;i<n; i++)
printf("%f\t", x[i]); printf("\
nMaximumprofitis:-%f",tp);
intmain() {
float weight[20], profit[20],
capacity;intnum,i, j;
floatratio[20],temp;
63
CS3401 ALGORITHM LABORATORY
printf("\nEnter the no. of objects:-
");scanf("%d",&num);
printf("\nEnterthewtsand profitsof
eachobject:-");for(i=0;i<num;i++){
scanf("%f%f",&weight[i],&profit[i]);
}
printf("\nEnter the capacityacity of knapsack:-
");scanf("%f",&capacity);
for(i=0;i<num;i++){
for (j = i + 1; j < num; j++)
{if(ratio[i]<ratio[j]){
temp =
ratio[j];ratio[j]=r
atio[i];ratio[i]=te
mp;
temp =
weight[j];weight[j]=
weight[i];weight[i]=t
emp;
temp =
profit[j];profit[j] =
profit[i];profit[i]=t
emp;
}
}
}
knapsack(num,weight,profit,capacity);getch();r
eturn(0);
}
64
CS3401 ALGORITHM LABORATORY
OUTPUT:
Conclusion:
ThustheCprogramforsolvingKnapsackproblemhasbeenexecutedsuccessfully.
65
CS3401 ALGORITHM LABORATORY