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

Ada Lab Manual Cse

The document outlines the vision and mission of an engineering institute and its computer science department, emphasizing the production of competent engineers and fostering research and innovation. It details the program educational objectives, outcomes, and specific outcomes for graduates, focusing on problem-solving, ethical practices, and lifelong learning. Additionally, it includes a practical course template for the Analysis and Design of Algorithms, specifying course objectives, experiments, assessment details, and sample C/C++ programs for algorithm implementation.

Uploaded by

suzusuzu7034
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Ada Lab Manual Cse

The document outlines the vision and mission of an engineering institute and its computer science department, emphasizing the production of competent engineers and fostering research and innovation. It details the program educational objectives, outcomes, and specific outcomes for graduates, focusing on problem-solving, ethical practices, and lifelong learning. Additionally, it includes a practical course template for the Analysis and Design of Algorithms, specifying course objectives, experiments, assessment details, and sample C/C++ programs for algorithm implementation.

Uploaded by

suzusuzu7034
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

ANALYSIS AND DESIGN OF ALGORITHMS

VISION OF THE INSTITUTE


“To produce top-quality engineers who are groomed for attaining excellence in their
profession and competitive enough to help in the growth of nation and global society.”

MISSION OF THE INSTITUTE


M1: To offer affordable high-quality graduate program in engineering with value education
and make the students socially responsible.
M2: To support and enhance the institutional environment to attain research excellence in
both faculty and students and to inspire them to push the boundaries of knowledge
base.
M3: To identify the common areas of interest amongst the individuals for the effective
industry- institute partnership in a sustainable way by systematically working together.
M4: To promote the entrepreneurial attitude and inculcate innovative ideas among the
engineering professionals.

VISION OF THE DEPARTMENT


“To adapt the evolutionary changes in computer science and expose the students to the cutting-
edge technologies to produce globally competent professionals.”

MISSION OF THE DEPARTMENT


M1: To ensure holistic professional education in the field of computer science &
engineering and produce efficient industry ready IT graduates capable of
solving societal problems to be a part of nation building.
M2: To provide an inspirational atmosphere in the department to nurture research and
innovation capabilities among students and faculties making them
good innovators and visionaries.
M3: To Establish a vibrant Industry-Academic relationships and collaborations among the
individuals having the opportunities to work on the latest
technologies and professional challenges with integrity.
M4: To Cultivate students with professional skills, foster innovative research endeavors,
and cultivate entrepreneurial capabilities.

AJIET, MANGALURU 1
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

After 4 years of graduation, graduates will be able to


PEO1: To develop in students, the ability to solve real life problems by applying fundamental
science and elementary strengths of computer science courses.
PEO2: To mould students, to have a successful career in the IT industry where graduates will
be able to design and implement the needs of society and nation.
PEO3: To transform students, to excel in a competitive world through higher education and
indulge in research through continuous learning process.

PROGRAM OUTCOMES (POs)


PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineering problems.

PO2: Problem Analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

PO3: Design/Development of Solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.

AJIET, MANGALURU 2
ANALYSIS AND DESIGN OF ALGORITHMS

PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.

PO7: Environment and Sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

PO9: Individual and Team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.

PO11: Project Management and Finance: Demonstrate knowledge and understanding of


the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.

PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES (PSOs)


At the end of the program, graduates will be able to

PSO1: Apply engineering principles, professional ethics and fundamental science in


designing systems and communication models (protocols).

AJIET, MANGALURU 3
ANALYSIS AND DESIGN OF ALGORITHMS

PSO2: Design and develop smart and intelligent based applications in computational
environment.

AJIET, MANGALURU 4
Template for Practical Course and if AEC is a practical Course Annexure-V

Analysis & Design of Algorithms Lab Semester 4


Course Code BCSL404 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Credits 01 Exam Hours 2
Examination type (SEE) Practical
Course objectives:
● To design and implement various algorithms in C/C++ programming using suitable development tools to
address different computational challenges.
● To apply diverse design strategies for effective problem-solving.
● To Measure and compare the performance of different algorithms to determine their efficiency and suitability
for specific tasks.
Sl.No Experiments
1 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm.
2 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.
3 a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's
algorithm.
b. Design and implement C/C++ Program to find the transitive closure using Warshal's
algorithm.
4 Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra's algorithm.
5 Design and implement C/C++ Program to obtain the Topological ordering of vertices in a given
digraph.
6 Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method.
7 Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method.
8 Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n
positive integers whose sum is equal to a given positive integer d.
9 Design and implement C/C++ Program to sort a given set of n integer elements using Selection
Sort method and compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.
10 Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort
method and compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.
11 Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sort
method and compute its time complexity. Run the program for varied values of n> 5000, and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.
12 Design and implement C/C++ Program for N Queen's problem using Backtracking.

@# 16032024
Template for Practical Course and if AEC is a practical Course Annexure-V

Course outcomes (Course Skill Set):


At the end of the course the student will be able to:
1. Develop programs to solve computational problems using suitable algorithm design strategy.
2. Compare algorithm design strategies by developing equivalent programs and observing running
times for analysis (Empirical).
3. Make use of suitable integrated development tools to develop programs
4. Choose appropriate algorithm design techniques to develop solution to the computational and
complex problems.
5. Demonstrate and present the development of program, its execution and running time(s) and
record the results/inferences.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be
deemed to have satisfied the academic requirements and earned the credits allotted to each subject/
course if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE
(Continuous Internal Evaluation) and SEE (Semester End Examination) taken together

Continuous Internal Evaluation (CIE):


CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments are
designed by the faculty who is handling the laboratory session and are made known to students at
the beginning of the practical session.
● Record should contain all the specified experiments in the syllabus and each experiment write-up
will be evaluated for 10 marks.
● Total marks scored by the students are scaled down to 30 marks (60% of maximum marks).
● Weightage to be given for neatness and submission of record/write-up on time.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed in
the syllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge will
carry a weightage of 60% and the rest 40% for viva-voce.
● The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
● The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is the total CIE
marks scored by the student.

Semester End Evaluation (SEE):


● SEE marks for the practical course are 50 Marks.

@# 16032024
Template for Practical Course and if AEC is a practical Course Annexure-V

● SEE shall be conducted jointly by the two examiners of the same institute, examiners are
appointed by the Head of the Institute.
● The examination schedule and names of examiners are informed to the university before the
conduction of the examination. These practical examinations are to be conducted between the
schedule mentioned in the academic calendar of the University.
● All laboratory experiments are to be included for practical examination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script
to be strictly adhered to by the examiners. OR based on the course requirement evaluation
rubrics shall be decided jointly by examiners.
● Students can pick one question (experiment) from the questions lot prepared by the examiners
jointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.
● General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and
result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks
and scored marks shall be scaled down to 50 marks (however, based on course type, rubrics shall be
decided by the examiners)
● Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to be
made zero.
The minimum duration of SEE is 02 hours

Suggested Learning Resources:


● Virtual Labs (CSE): http://cse01-iiith.vlabs.ac.in/

@# 16032024
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM 01-Design and implement C/C++ Program to find Minimum


Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm.

#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
printf("\n\tImplementation of Kruskal's algorithm\n");
printf("\nEnter the number of vertices:");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of minimun cost spanning tree are\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);

AJIET, MANGALURU 5
ANALYSIS AND DESIGN OF ALGORITHMS

if(uni(u,v))
{
printf("%d edge(%d,%d)=%d\n",ne++,a,b,min);
mincost+=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost=%d\n",mincost);
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

OUTPUT-
Implementation of Kruskal's algorithm

Enter the number of vertices:4

Enter the cost adjacency matrix:


0104
1020
0203
4030
The edges of minimun cost spanning tree are
1 edge(1,2)=1
2 edge(2,3)=2
3 edge(3,4)=3

Minimum cost=6

AJIET, MANGALURU 6
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM 02-Design and implement C/C++ Program to find Minimum


Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.

#include<stdio.h>
#include<stdlib.h>
int **a,n,*visited,**sel;
void prim(int src)
{
int i,j,count,min,u,v,sum,k;
count=0;
sum=0;
k=0;
visited[src]=1;
while(count<n-1)
{
min=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(visited[i]==1&&visited[j]!=1&&a[i][j]<min)
{
min=a[i][j];
u=i;
v=j;
}
}
}
sel[k][0]=u;
sel[k][1]=v;
sum+=a[u][v];
visited[v]=1;
k++;
count++;
}
if(sum<999)
{
printf("Spanning Tree Exists.\n");
printf("Sum of MST:%d\n",sum);
printf("Selected Edges:\n");
for(i=0;i<n-1;i++)
{

AJIET, MANGALURU 7
ANALYSIS AND DESIGN OF ALGORITHMS

printf("%d--%d\n",sel[i][0],sel[i][1]);
}
} else
{
printf("Spanning Tree Does Not Exist.\n");
}
}
int main()
{
int i,j;
printf("Number of vertices:");
scanf("%d",&n);
a=calloc(n,sizeof(int *));
for(i=0;i<n;i++)
{
a[i]=calloc(n,sizeof(int));
}
visited=calloc(n,sizeof(int));
sel=calloc(n,sizeof(int *));
for(i=0;i<n;i++)
{
sel[i]=calloc(2,sizeof(int));
}
printf("Cost Adjacency Matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
prim(0);
return 0;
}

OUTPUT-
Number of vertices:4
Cost Adjacency Matrix:
0124
999 1 3 5
2 3 0 999
4 5 999 0
Spanning Tree Exists.
Sum of MST:7

AJIET, MANGALURU 8
ANALYSIS AND DESIGN OF ALGORITHMS

Selected Edges:
0--1
0--2
0--3

PROGRAM 3a- Design and implement C/C++ Program to solve All-Pairs


Shortest Paths problem using Floyd's algorithm.

#include<stdio.h>
int min(int,int);
void floyds(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++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;
printf("\nEnter the number of vertices:");
scanf("%d",&n);
printf("\nEnter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;

AJIET, MANGALURU 9
ANALYSIS AND DESIGN OF ALGORITHMS

}
for(i=1;i<=e;i++)
{
printf("\nEnter the end vertices of edge %d with its weight\n",i);
scanf("%d %d %d",&u,&v,&w);
p[u][v]=w;
}
printf("\nMatrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\nTransitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
printf("\nThe shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n<%d,%d>=%d",i,j,p[i][j]);
}
}

OUTPUT-
Enter the number of vertices:4

Enter the number of edges:


7

Enter the end vertices of edge 1 with its weight


123

Enter the end vertices of edge 2 with its weight


218

Enter the end vertices of edge 3 with its weight

AJIET, MANGALURU 10
ANALYSIS AND DESIGN OF ALGORITHMS

232

Enter the end vertices of edge 4 with its weight


341

Enter the end vertices of edge 5 with its weight


412

Enter the end vertices of edge 6 with its weight


147

Enter the end vertices of edge 7 with its weight


315

Matrix of input data:


999 3 999 7
8 999 2 999
5 999 999 1
2 999 999 999

Transitive closure:
0 3 5 6
5 0 2 3
3 6 0 1
2 5 7 0

The shortest paths are:

<1,2>=3
<1,3>=5
<1,4>=6
<2,1>=5
<2,3>=2
<2,4>=3
<3,1>=3
<3,2>=6
<3,4>=1
<4,1>=2
<4,2>=5
<4,3>=7

PROGRAM 3b- Design and implement C/C++ Program to find the transitive
closure using Warshal's Algorithm.

AJIET, MANGALURU 11
ANALYSIS AND DESIGN OF ALGORITHMS

#include<stdlib.h>
#include<stdio.h>
int**a,n;
void warshall()
{
int i,j,k;
for(k=0;k<n;k++){
for(j=0;j<n;j++){
for(i=0;i<n;i++){
a[i][j]=a[i][j]||a[i][k]&&a[k][j];
}
}
}
}
void print_array()
{
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
int main()
{
int i,j;
printf("Number of vertices:");
scanf("%d",&n);
a=calloc(n,sizeof(int*));
for(i=0;i<n;i++){
a[i]=calloc(n,sizeof(int));
}
printf("Adjacency Matrix:\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&a[i][j]);
}
}
printf("Entered adjacency matrix:\n");
print_array();
warshall();
printf("Transitive closure matrix:\n");

AJIET, MANGALURU 12
ANALYSIS AND DESIGN OF ALGORITHMS

print_array();
return 0;
}

OUTPUT-
Number of vertices:4
Adjacency Matrix:
0100
0001
0000
1110
Entered adjacency matrix:
0 1 0 0
0 0 0 1
0 0 0 0
1 1 1 0
Transitive closure matrix:
1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1

PROGRAM 04-Design and implement C/C++ Program to find shortest


paths from a given vertex in a weighted connected graph to other vertices
using Dijkstra's algorithm.

#include<stdio.h>
#include<stdlib.h>
int **cost,n,*dist,*visited;
void dijkstras(int src)
{
int v,u,min,count;
for(v=0;v<n;v++)
{
dist[v]=cost[src][v];
}
visited[src]=1;
for(count=n-1;count>=1;count--)
{

AJIET, MANGALURU 13
ANALYSIS AND DESIGN OF ALGORITHMS

min=999;
for(v=0;v<n;v++)
{
if(visited[v]!=1&&dist[v]<min)
{
min=dist[v];
u=v;
}
}
visited[u]=1;
for(v=0;v<n;v++)
{
if(visited[v]!=1&&dist[v]>dist[u]+cost[u][v])
{
dist[v]=dist[u]+cost[u][v];
}
}
}
}
int main()
{
int i,j,src;
printf("Size of the graph:");
scanf("%d",&n);
cost=calloc(n,sizeof(int*));
for(i=0;i<n;i++)
{
cost[i]=calloc(n,sizeof(int));
}
visited=calloc(n,sizeof(int));
dist=calloc(n,sizeof(int));
printf("Enter the elements:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cost[i][j]);
}
}
printf("Source vertex:");
scanf("%d",&src);
dijkstras(src);
printf("Vertex\tDistance From Source\n");
for(i=0;i<n;i++)

AJIET, MANGALURU 14
ANALYSIS AND DESIGN OF ALGORITHMS

{
printf("%d\t%d\n",i,dist[i]);
}
return 0;
}

OUTPUT-
Size of the graph:7
Enter the elements:
0 2 999 3 999 999 999
2 0 9 999 1 4 999
999 9 0 999 999 3 999
3 999 999 0 5 999 7
999 1 999 5 0 999 4
999 4 3 999 999 0 6
999 999 999 7 4 6 0
Source vertex:0
Vertex Distance From Source
0 0
1 2
2 9
3 3
4 3
5 6
6 7

PROGRAM 05-Design and implement C/C++ Program to obtain the


Topological ordering of vertices in a given digraph.

#include<stdio.h>
#include<stdlib.h>
int **a,n,*visited,*res,*s,top=-1,k;
void dfs(int u)
{

AJIET, MANGALURU 15
ANALYSIS AND DESIGN OF ALGORITHMS

int v;
s[++top]=u;
visited[u]=1;
for(v=0;v<n;v++)
{
if(visited[v]!=1 && a[u][v]==1)
{
dfs(v);
}
}
res[k--]=s[top--];
}
void topological_sort()
{
int v;
for(v=0;v<n;v++)
{
if(visited[v]!=1)
{
dfs(v);
}
}
printf("The topological ordering is:\n");
for(v=0;v<n;v++)
{
printf("%d\n",res[v]);
}
}
int main()
{
int i,j;
printf("Number of vertices:");
scanf("%d",&n);
a=calloc(n,sizeof(int*));
for(i=0;i<n;i++)
{
a[i]=calloc(n,sizeof(int));
}
visited=calloc(n,sizeof(int));
res=calloc(n,sizeof(int));
s=calloc(n,sizeof(int));
printf("The elements:\n");
for(i=0;i<n;i++)
{

AJIET, MANGALURU 16
ANALYSIS AND DESIGN OF ALGORITHMS

for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
k=n-1;
topological_sort();
return 0;
}

OUTPUT-
Number of vertices:6
The elements:
010110
001000
000011
000010
000001
000000
The topological ordering is:
0
3
1
2
4
5

AJIET, MANGALURU 17
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM 06-Design and implement C/C++ Program to solve 0/1


Knapsack problem using Dynamic Programming method.

#include<stdio.h>
#include<stdlib.h>
int *p,*w,n,m,*sel;
int max(int a,int b)
{
return a>b?a:b;
}
void knapsack()
{
int i,j,v[n+1][m+1];
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
if(i==0||j==0)
{
v[i][j]=0;
}
else if(j<w[i])
{
v[i][j]=v[i-1][j];
}
else
{
v[i][j]=max(v[i-1][j],p[i]+v[i-1][j-w[i]]);
}
}
}
printf("The table is:\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
printf("%d\t",v[i][j]);
}
printf("\n");
}
printf("Maximum profit:%d\n",v[n][m]);
j=m;
for(i=n;i>=0;i--)

AJIET, MANGALURU 18
ANALYSIS AND DESIGN OF ALGORITHMS

{
if(v[i][j]!=v[i-1][j])
{
sel[i]=1;
j=j-w[i];
}
}
printf("The selected items are:\n");
for(i=1;i<=n;i++)
{
if(sel[i]==1)
{
printf("%d\t",i);
}
}
printf("\n");
}
int main()
{
int i;
printf("Number of items:");
scanf("%d",&n);
printf("Knapsack capacity:");
scanf("%d",&m);
p=calloc(n,sizeof(int));
w=calloc(n,sizeof(int));
sel=calloc(n,sizeof(int));
printf("Profit Array:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&p[i]);
}
printf("Weight Array:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
}
knapsack();
return 0;
}

OUTPUT-
Number of items:3
Knapsack capacity:4

AJIET, MANGALURU 19
ANALYSIS AND DESIGN OF ALGORITHMS

Profit Array:
25
20
40
Weight Array:
3
1
2

The table is:


0 0 0 0 0
0 0 0 25 25
0 20 20 25 45
0 20 40 60 60
Maximum profit:60
The selected items are:
2 3

PROGRAM 07-Design and implement C/C++ Program to solve discrete


Knapsack and continuous Knapsack problems using greedy approximation
method.

#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity;
int n,i,j;
printf("Enter the number of items:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Weight and Profit for item[%d]:\n",i);
scanf("%f %f",&weight[i],&profit[i]);
}
printf("Enter the capacity of knapsack:\n");
scanf("%f",&capacity);
for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(ratio[i]<ratio[j])
{

AJIET, MANGALURU 20
ANALYSIS AND DESIGN OF ALGORITHMS

temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;

temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;

temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
printf("Knapsack problems using Greedy Algorithm:\n");
for(i=0;i<n;i++)
{
if(weight[i]>capacity)
break;
else
{
Totalvalue=Totalvalue+profit[i];
capacity=capacity-weight[i];
}
}
if(i<n)
Totalvalue=Totalvalue+(ratio[i]*capacity);
printf("\nThe maximum value is:%f\n",Totalvalue);
return 0;
}

OUTPUT-
Enter the number of items:7
Enter Weight and Profit for item[0]:
2 10
Enter Weight and Profit for item[1]:
35
Enter Weight and Profit for item[2]:
5 15
Enter Weight and Profit for item[3]:
77
Enter Weight and Profit for item[4]:
16
Enter Weight and Profit for item[5]:
4 18
Enter Weight and Profit for item[6]:

AJIET, MANGALURU 21
ANALYSIS AND DESIGN OF ALGORITHMS

13
Enter the capacity of knapsack:
15
Knapsack problems using Greedy Algorithm:

The maximum value is:55.333332

PROGRAM 08-Design and implement C/C++ Program to find a subset of a


given set S = {sl , s2,.....,sn} of n positive integers whose sum is equal to a
given positive integer d.

#include<stdio.h>
#include<stdlib.h>
int *w,n,m,*sel;
void print_soln()
{
int i;
printf("Soln:");
for(i=0;i<n;i++)
{
if(sel[i]==1)
{
printf("%d\t",w[i]);
}
}
printf("\n");
}
void subset_sum(int ssf,int index)
{

AJIET, MANGALURU 22
ANALYSIS AND DESIGN OF ALGORITHMS

if(ssf+w[index]<=m)
{
sel[index]=1;
if(ssf+w[index]==m)
{
print_soln();
}
else
{
subset_sum(ssf+w[index],index+1);
}
sel[index]=0;
subset_sum(ssf,index+1);
}
}
int main()
{
int i;
printf("Number of elements:");
scanf("%d",&n);
w=calloc(n,sizeof(int));
sel=calloc(n,sizeof(int));
printf("The elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&w[i]);
}
printf("Desired Sum:");
scanf("%d",&m);
subset_sum(0,0);
return 0;
}

OUTPUT-

Number of elements:4
The elements:
3567
Desired Sum:15
Soln:3 5 7

AJIET, MANGALURU 23
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM 09-Design and implement C/C++ Program to sort a given set of


n integer elements using Selection Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the
time taken to sort. Plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int *a,n;
void swap(int* x,int* y)
{
int temp=*x;
*x=*y;

AJIET, MANGALURU 24
ANALYSIS AND DESIGN OF ALGORITHMS

*y=temp;
}
void selectionsort(int a[],int n)
{
int i,j,min;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
if(a[j]<a[min])
min=j;
swap(&a[min],&a[i]);
}
}
void print_array()
{
int i;
for(i=0;i<n;i++)
printf("%d \t",a[i]);
printf("\n");
}
int main()
{
int i;
float start,end,complexity;
printf("Enter the value of n:");
scanf("%d",&n);
a=calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
a[i]=rand()%20;
}
printf("The array is:\n");
print_array();
start=clock();
selectionsort(a,n);
end=clock();
printf("The sorted array is:\n");
print_array();
complexity=(end-start)/CLOCKS_PER_SEC;
printf("Complexity=%f\n",complexity);
return 0;
}

AJIET, MANGALURU 25
ANALYSIS AND DESIGN OF ALGORITHMS

OUTPUT-
Enter the value of n:6
The array is:
3 6 17 15 13 15
The sorted array is:
3 6 13 15 15 17
Complexity=0.000002

PROGRAM 10-Design and implement C/C++ Program to sort a given set of


n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the
time taken to sort. Plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.

AJIET, MANGALURU 26
ANALYSIS AND DESIGN OF ALGORITHMS

#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int *a,n;
int partition(int l,int r)
{
int i,j,p,temp;
i=l;
j=r+1;
p=a[l];
while(i<=j)
{
do
{
i++;
}
while(p>=a[i]);
do
{
j--;
}
while(p<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[l];
a[l]=a[j];
a[j]=temp;
return j;
}
void q_sort(int l,int r)
{
int s;
if(l<r)
{
s=partition(l,r);
q_sort(l,s-1);
q_sort(s+1,r);
}
}

AJIET, MANGALURU 27
ANALYSIS AND DESIGN OF ALGORITHMS

void print_array()

{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
int main()
{
int i;
float start,end,complexity;
printf("Enter the value of n:");
scanf("%d",&n);
a=calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
a[i]=rand()%20;
}
printf("The array is:\n");
print_array();
start=clock();
q_sort(0,n-1);
end=clock();
printf("The sorted array is:\n");
print_array();
complexity=(end-start)/CLOCKS_PER_SEC;
printf("Complexity=%f\n",complexity);
return 0;
}

OUTPUT-
Enter the value of n:6
The array is:
3 6 17 15 13 15
The sorted array is:
3 6 13 15 15 17
Complexity=0.000003

AJIET, MANGALURU 28
ANALYSIS AND DESIGN OF ALGORITHMS

PROGRAM 11-Design and implement C/C++ Program to sort a given set of


n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the
time taken to sort. Plot a graph of the time taken versus n. The elements can
be read from a file or can be generated using the random number generator.

#include<stdlib.h>
#include<stdio.h>
#include<omp.h>
int *a,n;
void merge(int l,int r,int m)
{
int i,j,k,*b;
i=l;
j=m+1;
k=l;
b=calloc(n,sizeof(int));
while(i<=m && j<=r)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
} else
{
b[k++]=a[j++];
}
}
while(i<=m)
{
b[k++]=a[i++];
}
while(j<=r)
{
b[k++]=a[j++];
}
for(i=l;i<k;i++)
{
a[i]=b[i];
}
}
void merge_sort(int l,int r)
{

AJIET, MANGALURU 29
ANALYSIS AND DESIGN OF ALGORITHMS

int m;
if(l<r)
{
m=(l+r)/2;
#pragma omp task
{
merge_sort(l,m);
}
#pragma omp task
{
merge_sort(m+1,r);
}
merge(l,r,m);
}
}
void print_array()
{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
int main()
{
int i;
double start,end;
printf("Number of items:");
scanf("%d",&n);
a=calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
a[i]=rand()%20;
}
printf("The unsorted array:\n");
print_array();
omp_set_num_threads(2);
start=omp_get_wtime();
merge_sort(0,n-1);
end=omp_get_wtime();
printf("The sorted array:\n");
print_array();
printf("Time elapsed=%lf\n",end-start);

AJIET, MANGALURU 30
ANALYSIS AND DESIGN OF ALGORITHMS

return 0;
}

OUTPUT-
cc -fopenmp P11.c
./a.out
Number of items:7
The unsorted array:
3 6 17 15 13 15 6

The sorted array:


3 6 6 13 15 15 17
Time elapsed=0.000004

PROGRAM 12-Design and implement C/C++ Program for N Queen's


problem using Backtracking.

#include<stdio.h>
#include<stdlib.h>
int *x,q=0,n;
int can_place(int p)
{
int i;
for(i=0;i<q;i++)
{
if(x[i]==p||x[i]-i==p-q||x[i]+i==p+q)
{
return 0;
}
}
return 1;
}
void print_board()
{
int i,j;
printf("Solution:\n");
for(i=0;i<n;i++)
{

AJIET, MANGALURU 31
ANALYSIS AND DESIGN OF ALGORITHMS

for(j=0;j<n;j++)
{
if(x[i]==j)
{
printf("Q");
}
else
{
printf("_");
}
}
printf("\n");
}
}
void n_queens()
{
int p;
for(p=0;p<n;p++)
{
if(can_place(p))
{
x[q]=p;
q++;
if(q==n)
{
print_board();
}
else
{
n_queens();
}
q--;
}
}
}
int main()
{
printf("Board size:");
scanf("%d",&n);
x=calloc(n,sizeof(int));
n_queens();
return 0;
}

AJIET, MANGALURU 32
ANALYSIS AND DESIGN OF ALGORITHMS

OUTPUT-
1.Board size:1
Solution:
Q

2.Board size:4
Solution:
_Q__
___Q
Q___
__Q_
Solution:
__Q_
Q___
___Q
_Q__

AJIET, MANGALURU 33

You might also like