Cs3401 Algorithms Lab Manual Final 1
Cs3401 Algorithms Lab Manual Final 1
LIST OF EXPERIMENTS
Aim:
To Implement Linear Search and to determine the time required to search for an element,
thenumberofelementsinthe listtobesearchedandplota graphofthetimetakenversusn.
Algorithm:
Step1:First,readthesearchelement(Targetelement)inthearray.
Step 2:Set anintegeri=0andrepeatsteps3to4tillireachesthe endofthe array.
Step3: Matchthekeywitharr[i].
Step4:Ifthekeymatches,returntheindex.Otherwise,incrementiby1.
Program:
#include<stdio.h>
#include<conio.h>
#include<time.h>#
include<stdlib.h>#
definemax20
intpos;
intlinsearch(int,int[],int);
voidmain()
{
intch=1;doublet;
intn,i,a[max],k,op,low,high,pos;clock_t,begin,end;clrscr()
;
while (ch)
{
printf(“\n............MENU\n1.LinearSearch\n2. Exit\n”);
printf(“\nEnterYourchoice\
n”);scanf(“%d”,&op);
switch(op)
{
Case 1:printf(“\n Enter the Number ofElements \
n”);scanf(“%d”,&n);
printf(“\n Enter the Elements of an Array\
n”);for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nEntertheElementtobeSearched\n”);
scanf(“%d”,&k);begin
=clock();pos=linsearc
h(n,a,k);end=clock();i
f(pos==-1)
printf(“\n\n Unsuccessful
Search”);else
printf(“Element%disfoundatposition%d”,k,pos+1);
printf(“\n Time Taken is %f CPU Cycles
\n”,(end-begin)/CLK_TCK);getch();
break;
default:printf(“InvalidChoiceEntered\
n”);exit(0);
}
printf(“\nDoyou wishtorunagain(1/0)\
n”);scanf(“%d”,&ch);
}
getch();
}
intlinsearch(intn, inta[],intk)
{
delay(1000);if(n<
0) return -
1;if(k==a[n-1])
return(n-1);
else
returnlinsearch(n-1,a,k);
}
Output:
***********MENU************
LinearSearch
Exit
EnterYourChoice1
Enterthenumberofelements3
Enterthenumberofanarrayintheorder256
998
Entertheelementstobesearched98
Element98 isfoundatposition3
TimeTakenis1.978022CPU1Cycles
Aim:
ToimplementrecursiveBinarySearchanddeterminethetimerequiredtosearchanelement.
Algorithm:
Step 1:Findthemiddleelementofarray.using middle=initial_value+ end_value/2;
Step2:Ifmiddle=element,return‘elementfound’andindex.
Step 3: if middle > element, call the function with end_value = middle - 1 .Step
4:ifmiddle< element,callthefunctionwithstart_value= middle+ 1.Step 5 :exit.
Program:
#include
<stdio.h>#include<
conio.h>#include<t
ime.h>#include<st
dlib.h>#definemax
20
intpos;
int
binsearch(int,int[],int,int,int);voi
dmain()
{
int
ch=1;dou
ble t;
intn,i,a[max],k,op,low,high,pos,clock_t,begin,end;
clrscr();w
hile(ch)
{
printf("\n........MENU\nl.BinarySearch\n2.Exit\n”);
printf("\nenteryourchoice\
n");scanf("%d",&op);
switch(op)
{
case1:printf("\nenter.thenumber ofelements\
n“);scanf(“%d"&n);
priritf("\nentertheelements inorder\
n");for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nentertheelementtobesearched\
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\
nUnsuccessfulSearch”);else
printf("\nelement%dis foundatposition%d”,k, pos+1);
printf("\nTimeTakenis%f CPUcycles\n”,(end-begin)/CLK_TCK);
getch();
break;
}
printf(''\nDoyouwishtorunagain(l/0)\n");
scanf("%d",&ch);
}
getch();
}
intbinsearch(intn,inta[],intk,intlow,inthigh)
{
intmid;delay(1
000);mid=(low
+high)/
2;if(low>high)
return -
1;if(k==a[mid])
return(mid);
elseif(k<
a[mid])
returnbinsearch(n,a,k,low,mid-1);
else
returnbinsearch(n,a,k,lmid+1,high);
}
Output:
***********MENU************
1.BinarySearch
2.Exit
EnterYourChoi
ce1
Enterthenumberofelements
3
Enterthenumberofanarrayintheorder
98
22
46
Entertheelementstobesearche
d22
Element22isfoundatposition2Tim
eTakenis1.978022CPUcycles.
3. Givenatexttxt[0...n-1]andapatternpat[0...m-1],writeafunctionsearch(charpat[],chartxt[])thatprints
alloccurrencesof pat[]intxt[].Youmayassumethatn>m.
Aim:
Toimplementfunctionsearchandtoprint all occurrences of thepattern in the given text.
Algorithm:
NAVE_STRING_MATCHING(T,P)
fori←0ton-mdo
ifP[1......m]==T[i+1..............i+m]then
print"MatchFoun
d"end
Program:
#include <stdio.h>
#include <string.h>
void search(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i<= N - M; i++)
{
int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M)
// if pat[0...M-1] = txt[i, i+1, ...i+M-1]
printf("Pattern found at index %d \n", i);
}
}
int main()
{char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}
OUTPUT:
Patternfoundatindex0P
attern found atindex
9Patternfound
atindex12
4. Sort a given set of elements using the Insertion sort and Heap sort methods and determinethe time
required to sort the elements. Repeat the experiment for different values of n, thenumberofelements
inthelisttobe sorted andplotagraph ofthetimetakenversusn.
Aim:
Tosorttheelementsusinginsertionsortandheapsort.
Algorithm:
InsertionSort:
Step1:Iftheelementisthefirstone, itisalreadysorted.
Step2:Movetonextelement.
Step3: Comparethecurrentelementwithallelements inthesortedarray.
Step4:Ifthe
elementinthesortedarrayissmallerthanthecurrentelement,iteratetothenextelement.Otherwise,shiftallthegreater
elementinthe arraybyonepositiontowardsthe right
Step 5 : Insert the value at the correct
position.Step 6 :Repeat until the complete list is
sorted.
Program:
#include<stdio.h>
voidinsert(int a[],int n)
{
inti,j,temp;
for(i=1;i<n; i++)
{temp= a[i];
j=i-1;
while(j>=0&&temp<=a[j])
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
}
voidprintArr(inta[],int n)
{
int i;
for (i = 0; i< n; i+
+)printf("%d",a[i])
;
}
intmain()
{
inta[20];
intn=sizeof(a)/sizeof(a[0]);
printf(“enter number of elements:”);
scanf(“%d”,&n);
printf(“enter the elements”);
for(int i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf("Beforesortingarrayelementsare- \
n");printArr(a,n);
insert(a,n);
printf("\nAftersortingarrayelementsare-\
n");printArr(a,n);
return0;
}
Output:
BeforeSorting
arrayelementsare12312583217
After
Sortingarrayelementsare812172
53132
HeapSort:
Algorithm:
Step1:Build a binary heap.
Step 2:Start iterating from mid to the start of the binary heap array.
Step3:On every iteration, swap the root node with the last leaf node.
Step 4: Remove the leaf node by putting it back at the end of the new sorted array.
Step 5: Again do the heapify operation and repeat the iteration from step 2.
Step 6: Exit
#include<stdio.h>
// function prototyping
voidheapify(int*,int,int);
voidheapsort(int*,int);
voidprint_array(int*,int);
intmain()
{
intarr[],CLK_TCK,end,start;
int n =sizeof(arr)/sizeof(arr[0]);
printf("enter no of elements");
scanf("%d",&n);
printf("enter elements");
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
heapsort(arr, n);
end=clock();
printf("\nTimetaken byHeapsortofCPUCycle”,(end-start)/CLK_TCK);
getch();
return0;
}
// now check whether the right and left right is larger than the root or not
if(left < n &&arr[left]>arr[largest])
{
largest = left;
}
// if the root is smaller than the children then swap it with the largest children's value
if(largest !=i)
{
int temp =arr[i];
arr[i]=arr[largest];
arr[largest]= temp;
// againheapify that side of the heap where the root has gone
heapify(arr, n, largest);
}
}
Output:
Enterthenumber
ofElements:3Enterthe
3Elements:
42
85
58
Sorted Elements
are425885
Timetaken byHeapsort 0.109890CPU Cycle.
GraphAlgorithms
1. Developaprogramtoimplement graphtraversalusingBreadthFirstSearch.
Aim:
ToDevelopaprogramtoimplementgraphtraversalusingBreadthFirstSearch.
Algorithm:
1. Firsttakethenumberofnodesinthegraphasinputandthencreateanadjacencymatrixofsizenxnwherenis
thenumberofnodesinthegraph.
2. Next taketheadjacencymatrixasinput.
3. Takethestarting nodeasinput.
4. Wethencallthebfsfunctionwiththestartingnodeastheargument.
5. Inthebfsfunction,wefirstmarkthecurrentnodeasvisitedandthenweenqueueallthenodeswhichare
adjacenttothecurrentnodeandarenotvisited.
6. Wethendequeueanodefromthequeueandcallthebfsfunctionwiththedequeuednodeastheargument.
7. Werepeattheabovestepsuntilthequeueisempty.
8. Finally, weprintthenodeswhicharereachablefromthestartingnode.
Program:
#include<stdio.h>
int n, i, j, visited[10], queue[10], front = -1, rear = -1;
intadj[10][10];
voidbfs(int v)
{
for(i= 1;i<=n;i++)
if(adj[v][i]&&!
visited[i])queue[+
+rear]= i;
if(front<=rear)
{
visited[queue[front]]=1;b
fs(queue[front++]);
}
}
voidmain()
{
int v;
printf("Enterthenumberofvertices:");sca
nf("%d",&n);
for(i= 1;i<=n;i++)
{
queue[i]=0;
visited[i]=0;
}
printf("Entergraphdatainmatrixform:\n");
for(i=1;i<=n;i++)
for (j = 1; j <= n; j+
+)scanf("%d",&adj[i]
[j]);
printf("Enterthestartingvertex:");sc
anf("%d",&v);
bfs(v);
printf("Thenodewhicharereachableare:\n");
for(i=1;i<=n;i++)
if
(visited[i])printf
("%d\t",i);
else
printf("BFS
isnotpossible.Notallnodesarereachable");return0;
}
Output:
Aim:
TodevelopaprogramtoimplementgraphtraversalusingDepthFirstSearch.
Algorithm:
Step 1:Createastackwiththetotalnumberofverticesinthegraphasthe size.
Step2:Chooseanyvertexasthetraversal'sbeginningpoint.Pushavisittothatvertexandaddittothe stack.
Step3:Pushanynon-visitedadjacentverticesofa vertexatthetopofthestacktothetopofthestack.
Step4:Repeatsteps3and4untiltherearenomoreverticestovisitfromthevertexatthetopofthestack.
Step5:Iftherearenonewverticestovisit,gobackandpoponefromthestackusingbacktracking.
Step 6:Continueusing steps3,4,and 5 untilthe stack isempty
Step7:Whenthestackisentirelyunoccupied,createthefinalspanningtreebydeletingthegraph'sunusededges.
Program:
#include<stdio.h>
#void DFS(int);
intG[10][10],visited[10],n;
voidmain()
{
inti,j;
printf("Enternumberofvertices:");scanf(
"%d",&n);
printf("\
nEnteradjecencymatrixofthegraph:");for(i=0;i<n;i++)
for(j=0;j<n;j+
+)scanf("%d",&G[i]
[j]);for(i=0;i<n;i+
+)visited[i]=0;
DFS(0);
}
voidDFS(inti)
{
intj;
printf("\n%d",i);
visited[i]=1;f
or(j=0;j<n;j++)
if(!visited[j]&&G[i]
[j]==1)DFS(j);
}
Output:
Enternumber ofvertices:8
Enteradjancencymatrixofthe graph:01111000
10000100
10000100
10000010
10000010
01100001
00011001
00000110
0
1
5
2
7
6
3
4
Processreturned 8(0x8)executiontime : 64.785 s
3.Fromagivenvertexinaweightedconnectedgraph,developaprogramtofindtheshortestpathstootherverti
ces usingDijkstra’s algorithm.
Aim:
Tofinda shortest path to other vertexinaweightedconnectedgraphusingDijkstra’salgorithm.
Algorithm:
Step 1:CreateasetshortPathtostore verticesthatcomeinthe wayoftheshortestpathtree.
Step 2 : Initialize all distance values as INFINITE and assign distance values as 0 for source
vertexsothatitispickedfirst.
Step 3 : Loop until all vertices of the graph are in the
shortPath.Program:
#include
<limits.h>#include
<stdbool.h>#include
<stdio.h>#defineV9
intminDistance(intdist[],boolsptSet[])
{
intmin=INT_MAX,min_index;
for(int v=0;v<V;v++)
if(sptSet[v]==false&&dist[v]<=min)min=
dist[v],min_index=v;
returnmin_index;
}
voidprintSolution(intdist[])
{
printf("Vertex\t\tDistancefromSource\
n");for(inti=0;i<V;i++)
printf("%d\t\t\t\t%d\n",i,dist[i]);
}
voiddijkstra(intgraph[V][V],intsrc)
{
intdist[V];bool
sptSet[V];
for(inti=0;i<V;i++)
dist[i]=INT_MAX,sptSet[i]=false;dist[src]=0;
for(intcount=0;count<V-1;count++)
{
intu=minDistance(dist,sptSet);
sptSet[u]=true;
for(intv=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);
}
intmain()
{
intgraph[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);
return0;
}
Output:
Vertex DistancefromSource
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
4.FindtheminimumcostspanningtreeofagivenundirectedgraphusingPrim’salgorithm.
Aim:
ToFindtheminimumcost spanningtreeofagivenundirectedgraphusingPrim’salgorithm.
Algorithm:
Step1:Determine anarbitraryvertexasthestartingvertexofthe MST.
Step2:Followsteps3to5tillthereareverticesthatarenotincludedintheMST(knownasfringevertex).
Step3:Findedgesconnectinganytreevertexwiththefringevertices.
Step4:Findtheminimumamongtheseedges.
Step5:Add thechosenedgeto theMSTifitdoesnot formanycycle.
Step6:ReturntheMSTandexit.
Program:
#include
<limits.h>#include
<stdbool.h>#include
<stdio.h>#defineV5
int minKey(intkey[],boolmstSet[])
{
intmin=INT_MAX,min_index;for(i
nt v=0;v<V;v++)
if(mstSet[v]==false&&key[v]<min)min=
key[v],min_index=v;
returnmin_index;
}
intprintMST(intparent[],intgraph[V][V])
{
printf("Edge \tWeight\
n");for(inti=1;i<V;i++)
printf("%d-%d\t%d\
n",parent[i],i,graph[i]
[parent[i]]);
}
voidprimMST(intgraph[V][V])
{
int
parent[V];i
ntkey[V];
boolmstSet[V];
for(inti=0;i<V;i++)
key[i]=INT_MAX,mstSet[i]=false;key[0
]=0;
parent[0]=-1;
for(intcount=0;count<V-1;count++)
{
intu=minKey(key,mstSet);ms
tSet[u]=true;
for(intv=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);
}
intmain()
{
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);
return0;
}
Output:
Edge Weight
0-1 2
1-2 3
0-2 6
1-3 5
5. ImplementFloyd’salgorithmfortheAll-Pairs-Shortest-Pathsproblem.
Aim:
ToimplementFloyd’salgorithmfortheAll-Pairs-Shortest-Pathsproblem.
Algorithm:
Step1:Initializetheshortestpathsbetweenany2verticeswithInfinity.
Step2:Findall pairshortestpathsthatuse0intermediatevertices,thenfindtheshortestpathsthatuse1intermediate
vertexandsoon..untilusingallNverticesasintermediate nodes.
Step3:Minimizetheshortestpathsbetweenany2pairsinthepreviousoperation.
Step4:
Forany2vertices(i,j),oneshouldactuallyminimizethedistancesbetweenthispairusingthefirstKnodes,sothesho
rtestpathwillbe:
min(dist[i][k]+dist[k][j],dist[i][j]).
dist[i][k]representstheshortestpaththatonlyusesthefirstKvertices,dist[k]
[j]representsthe shortestpathbetweenthe pairk,j.
Asthe shortestpathwillbe a concatenationofthe shortestpathfromitok,thenfromktoj.
Program:
#include <bits/stdc+
+.h>usingnamespace
std;#defineV4
void printSolution(int dist[]
[V]);voidfloydWarshall(intdist[]
[V])
{
inti,j,k;
for(k=0;k<V;k++)
{
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
{
if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF &&dist[i][k] != INF))dist[i]
[j]=dist[i][k]+dist[k][j];
}
}
}
printSolution(dist);
}
voidprintSolution(intdist[][V])
{
cout<<"Thefollowingmatrixshowstheshortest""distances""betweeneverypairofvertices\
n";for(inti=0;i<V;i++)
{
for(intj=0;j<V;j++)
{
if(dist[i][j]==INF)
cout<<"INF"<<"";
else
cout<<dist[i][j]<<"";
}
cout<<endl;
}
}
intmain()
{
int graph[V][V]={{0,5,INF,10},{INF,0,3,INF},{INF,INF,0,1},{INF,INF,INF,0}};
floydWarshall(graph);r
eturn0;
}
Output:
Thefollowingmatrixshowstheshortestdistancebetweeneverypairofvertices.
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
6.Computethetransitiveclosureofagivendirectedgraph usingWarshall'salgorithm.
Aim:
ToComputethetransitiveclosureofagivendirectedgraphusingWarshall'salgorithm.
Algorithm:
Program:
# include
<stdio.h>#include<
conio.h>
intn,a[10][10],p[10][10];
voidpath()
{
inti,j,k;for(i=0;i<n
;i+
+)for(j=0;j<n;j+
+)p[i][j]=a[i]
[j];for(k=0;k<n;k+
+)for(i=0;i<n;i+
+)for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1)p[i][j]=1;
}
voidmain()
{
int
i,j;clrscr
();
printf("Enterthenumberofnodes:");sc
anf("%d",&n);
printf("\nEntertheadjacencymatrix:\
n");for(i=0;i<n;i++)
for(j=0;j<n;j+
+)scanf("%d",&a[i]
[j]);path();
printf("\nThepathmatrixisshowmbelow\
n");for(i=0;i<n;i++)
{
for(j=0;j<n;j+
+)printf("%d ",p[i]
[j]);printf("\n");
}
getch();
}
Output:
Enterthenumberofnodes:4Entert
headjacencymatrix:
0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0
Thepathmatrixisshownbelow
1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1
AlgorithmDesignTechniques
1. Developaprogramtofindoutthemaximumandminimumnumbersinagivenlistofn
Numbersusingthedivideandconquertechnique.
Aim:
TodevelopaCprogramtofindout themaximum andminimum numbersin a given listofn
Numbersusingthedivideandconquertechnique.
Algorithm:
1. Setminand maxtoarr[0]
2. Start loopat1,usingindexi
i.Checkifarr[i]< min;ifso,setmintoarr[i]
ii.Checkifarr[i]>max;ifso,setmaxtoarr[i]
3. Atendofloop,respondwithanarraycontaining[min,max]
4. Ifthearrayis1elementlong,return[arr[0],arr[0] ]
5. Ifthearrayis2elementslong
i.Ifarr[0] >arr[1],return[ arr[1], arr[0]]
ii.Otherwise,returnarr
6. Splitthearrayroughlyintoalefthalfandrighthalf,callingminmaxoneachhalf
7. return[min(left[0],right[0]),max(left[1],right[1]]
Program:#include
<stdio.h>#include
<stdio.h>intmax,
min;
inta[100];
voidmaxmin(inti,intj)
{
intmax1,min1,mid;if(
i==j)
{
max=min=a[i];
}
else
{
if(i==j-1)
{
if(a[i]<a[j])
{
max=a[j];
min=a[i];
}
else
{
max=a[i];
min=a[j];
}
}
else
{
mid =
(i+j)/2;maxmin(i,
mid);
max1=max;min1=min;ma
xmin(mid+1,
j);if(max<max1)
max =
max1;if(min >
min1)min=mi
n1;
}
}
}
intmain()
{
inti,num;
printf("\
nEnterthetotalnumberofnumbers:");scanf("%d",
&num);
printf("Enterthenumbers:\n");
for (i=1;i<=num;i+
+)scanf("%d",&a[i]);
max=a[0];
min =
a[0];maxmin(1,n
um);
printf ("Minimum element in an array : %d\n",
min);printf("Maximumelementinanarray:%d\
n",max);return0;
}
Output:
Enterthe totalnumberof numbers :
72
88
82
85
65
Minimumelementinanarray:72Maximumel
ementinanarray:82
2. Implement Merge sort and Quick sort methods to sort an array of elements and determinethe time
required to sort. Repeat the experiment for different values of n, the number ofelementsinthe listtobe
sortedandplotagraphofthetimetakenversus n.
Aim:
TowriteaCprogramtoImplementMergesortandQuicksortmethodstosortanarrayofelementsanddetermineth
etimerequiredtosort.
Algorithm:
Step1:Findthemiddleindexofthearray.Middl
e=1+(last–first)/2
Step2:Dividethearrayfromthemiddle.
Step3:CallmergesortforthefirsthalfofthearrayMergeSort(
array,first,middle)
Step4:Callmergesortforthesecondhalfofthearray.MergeSort(array,middle+
1,last)
Step5:Merge thetwosortedhalvesintoa singlesortedarray.
Merge Sort:
step1:start
step2:declarearrayandleft,right,midvariablestep
3:performmergefunction.
if left >
rightretur
n
mid=
(left+right)/2mergesort(a
rray,left,mid)
mergesort(array,mid+1,right)
merge(array,left,mid,right)
step4:Stop
Program:
#include <stdio.h>
#include<time.h>
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
+
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 },clock_t,end,begin;
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
//begin=clock();
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
//end=clock();
//printf(“time taken of %f cycles”,(end-begin)/CLK_TK);
return 0;
}
Output:
Given array
is121113567
Sorted array
is567111213
QuickSort:
Algortihm:
Step 1: Consider the first element of the list as pivot (i.e., Element at first position in the
list).Step2:Definetwovariablesiandj.Setiand
jtofirstandlastelementsofthelistrespectively.Step3:Incrementiuntillist[i]>pivotthenstop.
Step4:Decrementjuntillist[j]<pivotthenstop.
Step5:Ifi< jthenexchangelist[i]andlist[j].
Step6:Repeatsteps3,4&5untili>j.
Step7:Exchangethepivotelementwithlist[j]element.
Program:#include<
stdio.h>#include<c
onio.h>
voidquickSort(int[10],int,int);v
oidmain(){
intlist[20],size,i;
printf("Entersizeofthelist:");sca
nf("%d",&size);
printf("Enter
%dintegervalues:",size);for(i=0;i<size;i+
+)scanf("%d",&list[i]);quickSort(list,0,si
ze-1);
printf("Listaftersortingis:");for
(i=0;i<size;i++)printf("
%d",list[i]);
getch();
}
Program:
#include <bits/stdc+
+.h>#define N4
usingnamespacestd;
voidprintSolution(intboard[N][N])
{
for (int i = 0; i< N; i++)
{for(intj=0;j<N;j++)
if(board[i]
[j])cout<< "Q
";elsecout<<".";
printf("\n");
}
}
boolisSafe(intboard[N][N],introw,intcol)
{
inti,j;
for(i=0;i<col;i++)if
(board[row]
[i])returnfalse;
for(i=row,j=col;i>=0&&j>=0;i--,j--)if(board[i]
[j])
returnfalse;
for(i=row,j=col;j>=0&&i<N;i++,j--)if(board[i]
[j])
return
false;returntrue
;
}
boolsolveNQUtil(intboard[N][N],intcol)
{
if (col >=
N)returntr
ue;
for (int i = 0; i< N; i++)
{if(isSafe(board,i,col)){
board[i][col]=1;
if(solveNQUtil(board,col+1))ret
urntrue;
board[i][col]=0;//BACKTRACK
}
}
returnfalse;
}
bool solveNQ()
{
intboard[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
if(solveNQUtil(board,0)==false)
{
cout<<"Solutiondoesnotexist";ret
urnfalse;
}
printSolution(board);
returntrue;
}
intmain()
{
solveNQ();
return0;
}
Output:
..Q.
Q...
...Q
.Q..
ApproximationAlgorithmsRandomizedAlgorithms
1. Implement any scheme to find the optimal solution for the Traveling Salesperson problemand then
solve the same problem instance using any approximation algorithm and
determinetheerrorintheapproximation.
Aim:
TofindthesolutionusingTravelingSalespersonProblemanddeterminetheerrorintheapproximation.
Algorithm:
Step1:Considercity1asthestartingandendingpoint.Sincetherouteiscyclic,
wecanconsideranypointasastartingpoint.
Step2:Generateall(n-1)!permutationsofcities.
Step3:Calculatethecostofeverypermutationandkeeptrackoftheminimumcostpermutation.Returntheper
mutationwithminimumcost.
Program:
#include <bits/stdc+
+.h>using namespace
std;#define V4
inttravllingSalesmanProblem(intgraph[][V],ints)
{
vector<int>vertex;
for(inti=0;i<V;i++)if(i!
=s)
vertex.push_back(i);int
min_path = INT_MAX;do{
intcurrent_pathweight=0;in
tk=s;
for (int i = 0; i<vertex.size(); i++)
{current_pathweight+=graph[k]
[vertex[i]];k=vertex[i];
}
current_pathweight+=graph[k][s];
min_path=min(min_path,current_pathweight);
}while(
next_permutation(vertex.begin(),vertex.end()));retur
nmin_path;
}
intmain()
{
// matrix representation of
graphintgraph[][V]={{0,10,15,20},
{10,0,35,25},
{15,35,0,30},
{20,25,30,0}};
ints=0;
cout<<travllingSalesmanProblem(graph,s)<<endl;retur
n0;
}
Output:
80
Aim:
Algorithm:
Step 1 :Partition the array A[left .. right] into two subarrays A[left .. pos] and A[pos + 1 .. right] such that each
element of A[left .. pos] is less than each element of A[pos + 1 .. right].
Step 2: Computes the number of elements in the subarray A[left .. pos] i.e. count = pos - left + 1 if (count == K),
then A[pos] is the Kth smallest element.
Step 3: Otherwise determines in which of the two subarrays A[left .. pos-1] and A[pos + 1 .. right] the Kth
smallest element lies.
Step 4: If (count > K) then the desired element lies on the left side of the partition.
Step 5: If (count < K), then the desired element lies on the right side of the partition. Since we already know i
values that are smaller than the kth smallest element of A[left .. right], the desired element is the (K - count)th
smallest element of A[pos + 1 .. right].
Step 6: Base case is the scenario of single element array i.e left ==right. return A[left] or A[right].
Program:
#include<stdio.h>
#include<conio.h>
int cmpfunc(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
int kthSmallest(int arr[], int N, int K)
{
qsort(arr, N, sizeof(int), cmpfunc);
return arr[K - 1];
}
int main()
{
int arr[] = { 12, 3, 5, 7, 19 };
int N = sizeof(arr) / sizeof(arr[0]), K = 2;
printf("K'th smallest element is %d", kthSmallest(arr, N, K));
return 0;
}
Output: K'th smallest element is 5
1.