Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Algorithm Lab Manual

The document outlines the syllabus and experiments for an Algorithm Laboratory course (CS3401), detailing objectives, course outcomes, and a list of experiments involving various algorithms such as searching, sorting, and graph algorithms. Each experiment includes aims, objectives, theories, algorithms, and example C programs with explanations of their time complexities. The document also includes mappings of course outcomes to program outcomes.

Uploaded by

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

Algorithm Lab Manual

The document outlines the syllabus and experiments for an Algorithm Laboratory course (CS3401), detailing objectives, course outcomes, and a list of experiments involving various algorithms such as searching, sorting, and graph algorithms. Each experiment includes aims, objectives, theories, algorithms, and example C programs with explanations of their time complexities. The document also includes mappings of course outcomes to program outcomes.

Uploaded by

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

INDEX

SNO PARTICULARS PAGE


NO
1 Vision and Mission of Institution
2 Vision and Mission of Department
3 Program Education Outcomes
4 Program Specific Outcomes
5 Program Outcomes
6 Syllabus
LIST OF EXPERIMENTS
EX.NO DATE NAME OF PAGE Cos POs & MARK SIGN
EXPERIMENT NO Mapp PSOs
ed Mapped
1 Linear Search
2 Binary Search Using
Recursive
3 Pattern Matching
4 a) InsertSort
4b) Heap Sort
5 Graph Traversal:
BreadthFirst
Traversal
6 Graph Traversal:
DepthFirstTravers
al
7 Dijkstra'salgorith
m
8 Minimum Spanning
Tree -
Prism’sAlgorithm
9 Floyd’s Algorithm-
All pairShortest
Path
10 WarshallAlgorit
hm-
transitiveclosure
11 Min/max using
divide
andconquermethod
12 a) MergeSort
12b) QuickSort
13 N-Queens Problem
usingBackTrackin
g
14 Approximation
algorithmfortravell
ingsalesman
problem
15 Randomizedalgorit
hmforkthsmallestel
ement
16 Knapsackproblem
usingGreedymetho
d
SYLLABUS
CS3401 ALGORITHMLABORATORY LTPC004

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

CS3401 ALGORITHM LABORATORY


2. problem andthen solve the same problem instance using any approximation algorithm and
determine theerrorinthe approximation.
3. Implement randomized algorithms for finding the kth smallest
number.

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

CS3401 ALGORITHM LABORATORY


DATE: LINEAR SEARCH
EXPT.NO:01

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:

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.

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:

Element is present at index 3

Time complexities: -Time complexity for linear search is denoted by O(n) as


everyelement inthe arrayiscomparedonlyonce.

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:

Element is present at index 3

Time complexities: -Time complexity for Binary Search using Recursive is


denotedbyO(log n)aseveryelement inthearrayis comparedonlyonce.

Conclusion:HencewehavestudiedandexecutedtheprogramforBinarySearch usingRecursive.

4
CS3401 ALGORITHM LABORATORY
DATE: PATTERN MATCHING
EXPT.NO:03

Aim:-Programto implementPatternMatching

Objective:TowriteaCprogramto performPatternMatching.

Theory:Patternsearchingisaverycrucial problemincomputerscience.Wheneverwe seek for


a string in notepad/word file or browser or database or in
someinformation,patternsearchingalgorithms areusedto showthesearchresults.

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*/

// C program for insertion


sort#include<math.h>
#include<stdio.h>

/*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;
}
}

// A utility function to print an array of size


nvoidprintArray(intarr[],int n)
{
int i;
for (i = 0; i< n; i+
+)printf("%d",arr[i]);
printf("\n");
}

/*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

Time complexities: - Time complexity for Insertion sort using Recursive is


denotedbyO(N^2)as everyelementin the arrayiscomparedonlyonce.

8
CS3401 ALGORITHM LABORATORY
Conclusion:HencewehavestudiedandexecutedtheprogramforInsertionsort.

DATE: HEAP SORT


EXPT.NO:4B

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:

Enter the limit: 6

Enter the elements:


87
11
CS3401 ALGORITHM LABORATORY
54
32
67
45
90

The sorted elements are:

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).

Conclusion:Hencewehavestudiedandexecutedtheprogram for heap sort.

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:

Enter the number of vertices:4

Enter graph data in matrix form:

0100
1100
0101
1001

Enter the starting vertex:1


The node which are reachable are:
1
2

Bfs is not possible


Bf's is not possible

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

Aim:-Programtoimplement graphtraversal usingDepthFirstSearch.

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

Enter the adjacency matrix:

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>

// Number of vertices in the


graph#defineV9

//A utilityfunctionto findthevertex withminimum


//distancevalue,fromthesetofverticesnotyetincluded
//inshortestpathtree
intminDistance(intdist[],boolsptSet[])
{
//Initializeminvalue

20
CS3401 ALGORITHM LABORATORY
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;

returnmin_index;
}

//A utilityfunction to printtheconstructeddistance


//array
voidprintSolution(intdist[])
{
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]);
}

//FunctionthatimplementsDijkstra'ssinglesource
//shortestpathalgorithmforagraphrepresentedusing
// adjacency matrix
representationvoiddijkstra(intgraph[V]
[V],intsrc)
{
intdist[V];// Theoutputarray.dist[i]willholdthe
//shortest
// distancefromsrctoi

bool sptSet[V];//sptSet[i] will betrueifvertexiis


//includedinshortest
// pathtreeorshortest distancefromsrcto iis
//finalized

//Initializeall distancesasINFINITEandstpSet[]as
//false
for (int i= 0;i<V; i++)
dist[i]=INT_MAX,sptSet[i]=false;

//Distanceofsourcevertex fromitselfisalways 0dist[src]=0;

//Findshortestpathforall vertices
for(int count=0; count< V -1; count++){

21
CS3401 ALGORITHM LABORATORY
//Picktheminimumdistancevertex fromtheset of

// Mark the picked vertex as


processedsptSet[u]= true;

//Update distvalueof theadjacentverticesof the


// pickedvertex.
for (int v= 0;v<V;v++)

//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:

Vertex Distance from Source

0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

Time complexities:-Time complexity for Dijkstra’s Algorithm is denoted by O(V2)


asevery elementinthearrayiscomparedonlyonce.

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;

/* Now we have to find min dis of each vertex from


eitherstartVertexorendVertexbyinitialisingnr[]array
*/

for(i=0;i<n; i++) {
if(cost[i][startVertex]<cost[i]
[endVertex])nr[i]=startVertex;
else
nr[i]=endVertex;
}

/* To indicate visited vertex initialisenr[] for them to 100


*/nr[startVertex]=100;
nr[endVertex]=100;
temp=99;
for (i = 1; i< n - 1; i++)
{for(j=0;j<n;j++){

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:

Enter the no. of vertices :4

Enter the costs of edges in matrix form:

4567
1234
4567
5889

The matrix is:


4567
1234
4567
5889

The min spanning tree is: -


101
204
305

Min cost: 10

Time Complexities:-The time required by algorithm Prim is O(n²), where n is


thenumber of vertices inthegraph G.

Conclusion:-ThustheCprogramtofind
theminimumspanningtreeusingprim’salgorithmhasexecutedsuccessfully.

29
CS3401 ALGORITHM LABORATORY
DATE: ALL PAIR SHORTEST PATH
EXPT.NO:9

Aim:-Program to implement all pair shortest path.

Objective:-WriteaCprogramtofindall pairsshortestpathusingFloyd’salgorithm.

Theory:-Floyd’s algorithm is applicable to both directed and undirected graphs provided


that they donot contain a cycle. It is convenient to record the lengths of shortest path in
an n- by- n matrix D calledthe distance matrix. The element dij in the ith row and jth
column of matrix indicates the shortest pathfrom the ith vertex to jth vertex (1<=i, j<=n).
The element in the ith row and jth column of the currentmatrix D(k-1) is replaced by the
sum of elements in the same row i and kth column and in the samecolumnj and thekth
column if andonly if thelattersum is smallerthan itscurrentvalue.

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:

Enter the end vertices of edge3 with its weight


245

Matrix of input data:

999999999
999999999
999 1 999

Transitive closure:

0 999999
999 0 999
999 1 0

The shortest paths are:

<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.

Theory: Warshall's algorithm is used to determine the transitive closure of a


directedgraphorallpathsin adirectedgraphbyusingtheadjacency
matrix.Forthis,itgeneratesasequenceofnmatrices.Where,nisusedtodescribethe numberof
vertices.

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.

Conclusion: Hence we have studiedand executed


theprogramforWarshallAlgorithmusingtransitive closure

36
CS3401 ALGORITHM LABORATORY
DATE: MAXIMUM AND MINIMUM
EXPT.NO:11

Aim:-Programtofindoutmaximumandminimumusing divideandconquerrule.

Objective:To writeaCprogramtofind outmaximumandminimum


usingthedivideandconquertechnique

Theory:Theproblem istofind themaximum and minimumnumber usingthe


divideandconquermethod.
Algorithm:

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:

enter the size of the array 7


enter the elements of the array
198 23 45 56 78 90 12

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.

Objective:To writeaCprogram toperformmergesortusingthe divideandconquertechnique.

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 the total numbers: 6

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)

Conclusion:-Thus theCprogramto performmergesortusing the divideand


conquertechniquehasexecutedsuccessfully.

45
CS3401 ALGORITHM LABORATORY
DATE: QUICK SORT
EXPT.NO:12B

Aim:-ProgramtoimplementQuicksort.

Objective:To writeaCprogramtoperform Quicksortusingthe divideandconquertechnique

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.

//Cprogram to sortanarrayusingQuickSort Algorithm//

#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

THE ARRAY ELEMENTS BEFORE SORTING:


12 45 678 77
THE ARRAY ELEMENTS AFTER SORTING:
81245 6777

Timecomplexities:-
QuicksorthasanaveragetimeofO(nlogn)onnelements.ItsworstcasetimeisO(n²).

Conclusion:Thusthe Cprogram toperform Quicksort usingthe divideand


conquertechniquehasbeencompletedsuccessfully.

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);

printf("\nEnter the Cost Matrix\n");for(i=0;i

<n;i++)
{
printf("\nEnterElementsofRow:%d\n",i+1);

for( j=0;j <n;j++)scanf("%d",&ary[i]


[j]);

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.

Theory:Analgorithmthatuses randomnumberstodecidewhat todonextanywhereinits


logiciscalledRandomizedAlgorithm.

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);

// Return k'th element in the sorted


arrayreturnarr[K- 1];
}
59
CS3401 ALGORITHM LABORATORY
// Driver's
codeintmain()

{
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:

Kth smallest element is 5

Timecomplexities:-
TimecomplexityforRandomizedalgorithmforkthsmallestelementisdenotedbyO(Nlog N)as
everyelement inthearrayis comparedonly once.

Conclusion:Hence wehavestudiedand executedtheprogram


forRandomizedalgorithmforkthsmallestelement.

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;

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


{if(weight[i]>u)
break;
else{
x[i]=1.0;
tp= tp+profit[i];u
=u- weight[i];
}
}

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++) { ratio[i]


=profit[i]/ weight[i];
}

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:

Enter the no. of objects:- 4

Enter the wts and profits of each object:-


212
3 10
1 20
4 15

Enter the capacity of knapsack:- 15

The result vector is:- 1.000000 1.0000001.0000001.000000

Maximum profit is:- 57.000000

Conclusion:
ThustheCprogramforsolvingKnapsackproblemhasbeenexecutedsuccessfully.

65
CS3401 ALGORITHM LABORATORY

You might also like