Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

It1501 - Daa Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

DEPARTMENT

OF
INFORMATION TECHNOLOGY

LABORATORY MANUAL CUM RECORD


(AS PER OUTCOME BASED EDUCATION - OBE)

Lab Course Code

IT1501

Lab Course Name

DESIGN AND ANALYSIS OF ALGORITHMS LAB


DEPARTMENT : _____________________________

NAME : _____________________________

REGISTER NUMBER : _____________________________

ROLL NO (SECTION) : _____________________________

BRANCH : _____________________________

YEAR : _____________________________

SEMESTER : _____________________________

Bona-fide Record of work done in the ___________________________________________


of KAMARAJ College of Engineering and Technology, Near Virudhunagar, during the Academic
Year 20 - 20 .

COURSE -INCHARGE HEAD OF THE DEPARTMENT

Submitted for the Practical Examination held on ___________________ at


KAMARAJ College of Engineering and Technology, Near Virudhunagar.

INTERNAL EXAMINER EXTERNAL EXAMINER


CONTENT

Section: 1 Course Introductions

i. Introduction of Course

ii. Syllabus - List of Experiment - Reference books

Section: 2 Outcome Based Education (OBE)

i. Vision, Mission of Institution, Department, PEO’s


ii. OBE - Outcome Based Education - Introduction
iii. Program Outcome - PO, PSO
iv. Course Outcome - Course Objectives, Course Outcome (CO)
Mapping of CO vs PO - CO-PO Matrix (Calculation of Expected
POs Value)
v. Demonstration of - CO Attainment (Internal Assessment),
Action Plan
vi. Rubrics for Experiments

Section: 3 Safety Instructions

Section: 4 Laboratory Experiments Skill Development

i. Experiments
(Planning - Aim; Apparatus required; Theory; Procedure;
diagram;
Execution - calculation; formula, table; graph; report;
Monitoring - Viva Questions;
Assessment - Rubrics- Mark allotted and awarded; signature with
date
Observations - by student)
INDEX

CO
Ex. Page Mark
Date Title of the Exercise Attained? Sign
No. No. (100)
(Yes / No)

Implementation of Knapsack Problem


1
using Brute Force Technique

Implement Merge and Quick Sort


2 Algorithms and Compare the Time
Complexity for Various of N Values

Implementation of Warshall‘s and Floyd‘s


3 Algorithm using Dynamic Programming
Technique

Implementation of Djikstra’s Algorithm


4
using Greedy Technique
Implementation of Stable Marriage
5 Problem using Iterative Improvement
Technique

Implementation of N-Queens Problem


6
using Backtracking Technique
Laboratory Specific Instructions to Students
1) Students are required to remove their footwear outside the centre.
2) Students are asked to register their Name, Roll Number & System Number in the log
register before logging into the system.
3) Students should leave their belongings outside the lab except their Lab Manuals & Lab
File.
4) Students are requested not to place their legs on the wall or on the table.
5) Students should refrain from leaning on the table and sitting on it.
6) Before logging in to a particular terminal, if there is something wrong in the terminal, the
student should report the same immediately to the concerned staff.
7) Students should not use any disks brought from outside without prior permission from the
concerned staff.
8) Students should not move from their terminal and ask any clarification from their
friends/neighbour without any proper permission from the concerned staff.
9) Students should collect their printouts before leaving the lab for that particular session.
10) Before leaving the terminal, the students should logout properly and leave their chairs in
position.
11) Students are not allowed to use pen drive in any of the systems in the lab.
12) Students are not allowed to take any manual outside the centre.
13) Edibles are strictly prohibited in the centre.
14) Mobile Phones usage is strictly prohibited inside the lab. In case of any violence, the mobile
phone will be seized or broken.
15) No internet browsing is allowed during the lab hours.
Section: 1 Course Introductions

Introduction of Lab Course


Course Code
: IT1501
(As per Curriculum)
Course Code
: 20ITC302
(As per NBA)
Course Name : DESIGN AND ANALYSIS OF ALGORITHMS LAB

Importance of Course (150 Words write up)

1. Nowadays algorithm plays a vital role in computer science, used to solve the problems.

2. Algorithm plays a vital role in solving the problems. So we have to design an algorithm very
effectively and efficiently.

3. The main parameters used for analysis the algorithms are time and space required for that
algorithm.

4. Brute Force is a trial and error method used by application programs. A straightforward
approach, usually based directly on the problem’s statement and definitions of the concepts
involved.

5. Divide and Conquer means, we are dividing the problem inputs into smaller distinct subsets.
These sub problems are the solved, finally combined together to produce the solution for the whole
problem.

6. Dynamic Programming method is used when the solution to a problem can be viewed as the
result of a sequence of decisions. This method generates many decision sequences.

7. Greedy Method is straight forward method to solve the problem. In which we need to find the
feasible solution. Any subsets that satisfy these constraints called as feasible solution.

8. Iterative Improvement is a design technique for solving optimization problems. It starts with a
feasible solution. Repeat the following step until no improvement can be found.

9. Backtracking is a general algorithm for finding all solutions to some computational problem,
that incrementally builds candidates to the solutions, and abandons each partial candidate c
("backtracks") as soon as it determines that c cannot possibly be completed to a valid solution.

10. Branch and Bound is a general algorithm for finding optimal solutions of various optimization
problems, especially in discrete and combinatorial optimization. Approximation Algorithm is a
way of dealing with NP-completeness for an optimization problem. This technique does not
guarantee the best solution.
Lab Course Syllabus - List of Experiments
Course Code
: IT1501
(As per Curriculum)
Course Code
: 20ITC302
(As per NBA)
Course Name : DESIGN AND ANALYSIS OF ALGORITHMS LAB

The goal of this course is to have students understand and


appreciate the principles in the design and implementation of
Aim :
operating systems software.

Learn the algorithm analysis techniques


Objectives : Become familiar with the different algorithm design techniques
Understand the limitations of Algorithm power
List of Experiments :
1. Implementation of Knapsack Problem using Brute Force
Technique

2. Implement Merge and Quick Sort Algorithms and Compare the


Time Complexity for Various of N Values

3. Implementation of Warshall‘s and Floyd‘s Algorithm using


Dynamic Programming Technique

4. Implementation of Huffman Tree using Greedy Technique

5. Implementation of Stable Marriage Problem using Iterative


Improvement Technique

1. Anany Levitin, 2012, Introduction to the Design and Analysis of


Algorithms, 3rd ed, Pearson Education.
Reference Book :
2. Ellis Horowitz, Sartaj Sahni & Sanguthevar Rajasekaran, 2007,
Computer Algorithms/ C++, 2nd ed, Universities Press.

***********
Section: 2 Outcome Based Education (OBE)

VISION & MISSION & QUALITY POLICY OF THE COLLEGE

To Make this Institution the unique of its kind in the field of Research and
Vision :
Development activities in this part of world

To impart highly innovative and technical knowledge to the urban and


Mission :
unreachable rural student folks through "Total Quality Education".
Quality Committed to impart Quality Technical Education imbibed with proficiency,
:
Policy human values and continual improvement.

VISION & MISSION OF THE DEPARTMENT


To make the department of Information Technology the unique of its kind in
Vision :
the field of Research and Development activities in this part of world

To impart highly innovative and technical knowledge in the field of


Mission Information Technology to the urban and unreachable rural student folks
:
through Total Quality Education.

PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)

Graduates of the programme will exhibit expertise in technical knowledge by


PEO -1 :
applying distinctive skills in various fields of Information Technology.

PEO -2 : Graduates will become pioneers in the field of IT by working collaboratively and
providing solutions to meet societal needs through persistent learning

Graduates will be able to adopt innovative practices and contribute towards


PEO -3 : research and technological development in the field of IT through Total Quality
Education

*********************
OBE - Outcome Based Education - Introduction
Aim:
i. Outcomes are more like signboards and roadmaps to help the learners reach where
they’re supposed to reach, and contribute to progress.
ii. Outcome measurements provide the basis for continuous improvement in the
quality of learning
Terminology Description
i. With the introduction of the Washington accords, our higher
education demands better, intelligent workflows for the sake of
improving quality
ii. The accreditation and regulatory organisations including NBA,
Accreditation NAAC, AICTE etc. has clearly made their intentions clear about
introducing a skill-based, competency nurturing learning
experience
iii. As of the NBA, their accreditation methods and assessment
parameters are based on OBE

i. Deciding outcomes for academic achievements and it’s attainment


for assessment and formulation is based on a learning theory
called Outcome Based Education(OBE)
ii. OBE is an educational theory that bases each part of an educational
system around goals (outcomes).
OBE-
iii. Student role: By the end of the educational experience, each
Outcome
Based student should have achieved the goal. There is no single specified
Education
style of teaching or assessment in OBE; instead, classes,
opportunities, and assessments should all help students achieve the
specified outcomes.
iv. Faculty role: The role of the faculty adapts into instructor, trainer,
facilitator, and/or mentor based on the outcomes targeted.

i. Stating what you want your students to be able to do at the end


of the program.
OBE ii. Assessing the students whether they are able to do what they are
Emphasizes
expected to do to do what they are expected to do.
on
iii. Orienting teaching and other academic processes to facilitate
students to do what they are expected to do.
i. An objective is more like a plan, or a road map to reach/attain the
outcomes.
Course ii. A course objective describes what a faculty member will cover in a
Objectives
course. They are generally less broader than desirable goals and
more broader than student learning outcomes.

i. Outcome - A detailed description of what a student must be able to


do at the conclusion of a course.
ii. POs are attained through program specific Core Courses, which has
their own, previously set outcomes to attain. These course-specific
outcomes are called Course Outcomes.
Course iii. No. of CO Statements: Each course is designed to meet (about 5 -
Outcomes 6) Course Outcomes.
(COs) iv. Structure of COs Statements: The Course Outcomes are stated in
such a way that they can be actually measured. (SMART - S-
Specific; M-Measurable; A-Achievable; R-Realistic; T-Time
bound”)
v. Framing of COs: COs are set by the institution, by consulting with
the department heads, faculty, students and other stakeholders.

i. POs are statements about the knowledge, skills and attitudes


(attributes) the graduate of a formal engineering program should
have.
Program ii. POs deal with the general aspect of graduation for a particular
Outcomes program, and the competencies and expertise a graduate will
(POs) possess after completion of the program.
iii. These are broad and cover a wider area than of COs. the NBA has
set 12 Program Outcomes or Graduate Attributes for the sake of
unity and quality assurance.

i. Map the objective to the outcomes to analyse and document their


attainment
ii. Each CO can be identified to address a subset of POs
iii. Based on the number of COs and sessions dedicated to them , it is
Mapping of possible to identify the strength of mapping (1,2 or 3) to POs
CO vs PO
iv. Based on these strengths of selected POs a CPO matrix can be
established. PO matrix can be established
Course PO1 PO2 PO3 PO11 PO12
CO1 1 0 3 1 2 3 2
i. Program Educational Objectives (PEO) are statements that
describe the career and professional accomplishments that the
program is preparing the graduates to achieve.
ii. Measuring PEOs: PEO’s are measured 4 - 5 years after
Program graduation.
Educational
iii. They are set in order to measure the effectiveness of the program,
Objectives
(PEOs) and to check whether it has prepared the students to deal with
the real world, where they could apply and use the skills and
knowledge they’ve learned to good use.
iv. No. of PEOs: Each program shall specify 2 - 4 program specific
outcomes for the accreditation by the NBA.

CO Assessment:
i. The assessments should be in alignment with the COs
ii. Question paper should be so set to assess all COs
iii. The average marks obtained in assessments against items for each
CO will indicate the CO attainment

CO Attainment Gaps:
CO
Attainment iv. Instructors can set targets for each CO of his/her course
v. Attainment gaps can therefore be identified
vi. Instructor can plan to reduce the attainment gaps or enhance
attainment targets enhance attainment targets

CO Attainment:
vii. If the assessment is in alignment with COs, the performance of the
students indicates the CO attainment
Program Outcome (PO)
(Graduate Attributes)
At end of the laboratory course,
PO / Engineering Graduate will be able Learning attained the Outcomes / Skill of
PSO to: Level the Student -
(Remark by Students)
Engineering knowledge: Apply the
knowledge of mathematics, science,
engineering fundamentals and an K3
PO 1
engineering specialization for the - Apply
solution of complex engineering
problems.
Problem analysis: Identify,
formulate, research literature and
analyze complex engineering
K4
PO 2 problems reaching substantiated
- Analyze
conclusions using first principles of
mathematics, natural sciences and
engineering sciences.
Design/development of solutions:
Design solutions for complex
engineering problems and design
system components or processes that
K5
PO 3 meet the specified needs with
-Evaluate
appropriate consideration for public
health and safety, and cultural,
societal, and environmental
considerations.
Conduct investigations of complex
problems: Use research-based
knowledge and research methods
K5
PO 4 including design of experiments,
- Evaluate
analysis and interpretation of data,
and synthesis of the information to
provide valid conclusions.
Program Outcome (PO)
(Graduate Attributes)
At end of the laboratory course,
PO / Engineering Graduate will be able Learning attained the Outcomes / Skill of
PSO to: Level the Student -
(Remark by Students)
Modern tool usage: Create, select
and apply appropriate techniques,
resources and modern engineering
K6
PO 5 and IT tools, including prediction
- Create
and modeling to complex
engineering activities, with an
understanding of the limitations.
The engineer and society: Apply
reasoning informed by the contextual
knowledge to assess societal, health,
K3
PO 6 safety, legal and cultural issues and
- Apply
the consequent responsibilities
relevant to the professional
engineering practice.
Environment and sustainability:
Understand the impact of the
professional engineering solutions in
K2
PO 7 societal and environmental contexts,
Understand
and demonstrate the knowledge of,
and need for sustainable
development.
Ethics: Apply ethical principles and
commit to professional ethics and K3
PO 8
responsibilities and norms of the - Apply
engineering practice.
Individual and team work:
A3
PO 9 Function effectively as an individual,
-Value
and as a member or leader in diverse
Program Outcome (PO)
(Graduate Attributes)
At end of the laboratory course,
PO / Engineering Graduate will be able Learning attained the Outcomes / Skill of
PSO to: Level the Student -
(Remark by Students)
teams, and in multidisciplinary
settings.
Communication: Communicate
effectively on complex engineering
activities with the engineering
community and with the society at
A3
PO 10 large, such as, being able to
- Value
comprehend and write effective
reports and design documentation,
make effective presentations, and
give and receive clear instructions.
Project management and finance:
Demonstrate knowledge and
understanding of the engineering and
management principles and apply K3
PO 11
these to one’s own work, as a - Apply
member and leader in a team, to
manage projects and in
multidisciplinary environments.
Life-long learning: Recognize the
need for, and have the preparation A5
PO 12 and ability to engage in independent
Characterize
and life-long learning in the broadest
context of technological change.
Program Specific Outcome
(PSOs)
At the end of the program, the
student

Demonstrate technical and K4


PSO 1
interpersonal skills to design and - Analyze
Program Outcome (PO)
(Graduate Attributes)
At end of the laboratory course,
PO / Engineering Graduate will be able Learning attained the Outcomes / Skill of
PSO to: Level the Student -
(Remark by Students)
develop IT enabled solutions to meet
the real time industrial and societal
needs

Exhibit an ability to adapt to the K5


PSO 2
evolutionary changes in computing - Evaluate

Flow Chart - Attainment of Program Educational Objectives (PEO’s) through


PO & CO
Course Outcome (COs)
Course Code
: IT1501
(As per Curriculum)
Course Code
: 20ITC302
(As per NBA)
Course Name : DESIGN AND ANALYSIS OF ALGORITHMS LAB

Course Objectives
• Practice basic commands of operating systems, execute system calls of UNIX operating
system and practice basic shell programming
• Implement process synchronization mechanisms in operating systems
• Learn various process management schemes in operating systems
• Practice with different memory management mechanisms
• Implement the file allocation techniques

Course Outcomes
On successful completion of this course, students will be able to

CO CO Statements Learning Level

20ITC302.1 Identify the time and space complexity of computational problems K3 - Apply

Make use of brute force and divide and conquer techniques for
20ITC302.2 K3 - Apply
sorting and searching problems
Apply greedy and dynamic programming techniques for graph and
20ITC302.3 K3 - Apply
combinatorial problems
Identify the roles of iterative improvement technique to solve
20ITC302.4 K2 - Understand
optimization problems
Explain the use of backtracking, branch & bound and
20ITC302.5 approximation techniques to overcome the limitations of np- K2 - Understand
complete and np-hard problems

Laboratory Assessment Tool


S. No. Assessment Tool Weightage (%)
1 Lab Record & Observation 75%
2 Model Exam 25%
CO - PO Mapping
Program
Program Outcomes Specific
Outcomes
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO
(K3) (K4) (K5) (K5) (K6) (K3) (K2) (K3) (A3) (A3) (K3) (K5) (K3) (K5)

20ITC302.1 H M - M - - - - L - - M M -

20ITC302.2 H M M M - - - - L - - M H -

20ITC302.3 H M M M - - - - L - - M H -

20ITC302.4 H M M M - - - - L - - M H -

20ITC302.5 H M M M - - - - L - - M H L

CO - PO Mapping
Program
Program Outcomes Specific
Outcomes
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO
(K3) (K4) (K5) (K5) (K6) (K3) (K2) (K3) (A3) (A3) (K3) (K5) (K3) (K5)
20ITC302.1 3 2 - 2 - - - - 1 - - 2 3 -
20ITC302.2 3 2 2 2 - - - - 1 - - 2 3 -
20ITC302.3 3 2 2 2 - - - - 1 - - 2 3 -
20ITC302.4 3 2 2 2 - - - - 1 - - 2 3 -
20ITC302.5 3 2 2 2 - - - - 1 - - 2 3 1
Average 3 2 2 2 - - - - 1 - - 2 3 1

Target Value = 80 % of Marks

Note: Target Value = 80 %


If CO Attainment,
YES = Laboratory Mark (%) >= Target Value (%) NO = Laboratory Mark (%) < Target Value (%)
LIST OF EXPERIMENT & ITS CO
Marks
Bloom’s CO
S. Course Obtained
EXPERIMENT NAME Taxonomy Attained?
No. Outcome Out of
Level (Y/N)
[100]
Implementation of Knapsack Problem
1 20ITC302.1 K3 - Apply
using Brute Force Technique
Implement Merge and Quick Sort
2 Algorithms and Compare the Time 20ITC302.2 K3 - Apply
Complexity for Various of N Values
Implementation of Warshall‘s and
3 Floyd‘s Algorithm using Dynamic 20ITC302.3 K3 - Apply
Programming Technique
Implementation of Djikstra’s Algorithm
4 20ITC302.4 K3 - Apply
using Greedy Technique
Implementation of Stable Marriage
5 Problem using Iterative Improvement 20ITC302.4 K3 - Apply
Technique
Implementation of N-Queens Problem
6 20ITC302.5 K3 - Apply
using Backtracking Technique
CO ATTAINMENT - INTERNAL ASSESSMENT EVALUATION SHEET

Marks Average CO
Course
EXPERIMENT NAME Obtained of Each Attained?
Outcome (Y/N)
Out of 100 CO
Implementation of Knapsack Problem using
20ITC217.1
Brute Force Technique
Implement Merge and Quick Sort Algorithms
20ITC217.2 and Compare the Time Complexity for
Various of N Values
Implementation of Warshall‘s and Floyd‘s
20ITC217.3 Algorithm using Dynamic Programming
Technique
Implementation of Huffman Tree using
20ITC217.4
Greedy Technique
Implementation of Stable Marriage Problem
20ITC217.4
using Iterative Improvement Technique
Implementation of N-Queens Problem using
20ITC217.5
Backtracking Technique

Over All Total

Average Mark (Out of 100) - (A)

Co Attainment (Internal Assessment) Evaluation

Experiment Model Exam CO Attained


A B C D
Assessment Assessment
Mark E=((B+D)
Mark Obtained Weightage Weightage *0.20)
Obtained
(100) (80% of 100 (20% of Marks
(100)
Marks Obtained) Obtained)

Measuring Tools for CO Attainment (Components & Weight Age)


Internal
External
Experiment - 75% 20% 80%
University Exam
Model Exam - 25%
Action Plan:
(If CO Not Attained)

Reason for not


CO Attaining CO Remedial Action Plan Remarks Signature

Rubrics of Laboratory Experiments


Course Code
: IT1501
(As per Curriculum)
Course Code
: 20ITC302
(As per NBA)
Course Name : DESIGN AND ANALYSIS OF ALGORITHMS LAB
RUBRICS
CATEGORY
Explains the basic Explains the basic
Explains the basic Explains the basic
concept correctly but concept and unable
Logic concept and logic concept correctly but
lacks in presenting to make out the
[30] of the code programming logic
the logic correctly programming logic
correctly [30] is incorrect [25]
[28] [23]
Written code that Code deigned Code designed with Code designed with
Code
satisfies the entire satisfies the logic some logic mistakes some logic mistakes
Design
logic and 100% test and satisfies 75% and satisfies 50% and satisfies 25%
[30]
cases [30] test cases [28] test cases[25] test cases [23]
Explains all basic Explains all basic
Explains all basic Explains the basic
Viva concepts and concepts and the
concepts clearly but concepts alone but
Voce presented the logic logic of the code but
unable to explain the no logic explanation
[20] of the code unable to present it
complete logic [15] [13]
coherently [20] coherently [18]
Record Submission Delayed
On Date 3 Days Delayed 6 Days Delayed
Submissi More than a Week
Submission [20] Submission [18] Submission [15]
on [20] [13]
Total Marks: 100 Marks
Section: 3 Safety Instructions

The Institute works with several hazardous materials and equipment. Safety is an important
part of any training in research. Potential job givers, be it industry or academia, expect a certain
awareness about safety.

With guidance of AICTE - Office of Laboratory Safety and Environmental Health


(OLSEH), Our College has embarked on a concerted effort to improve the safety culture in our
academics and Research lab.

1. Safety OLSEH suggested that the four essential principles of safety must be
Principles follow for academics labs of institutions:
To prevent confusion, this manual clearly defines standards for safe work
practices. These rules need to be followed by everyone.
Follow Rules
“Remember practicing safety means doing things the right way, not
the quick way”

The primary responsibility for safety rests with the individual. A

Personal responsible, considerate worker with an understanding of the working of


Responsibility the laboratory, its equipment, basic chemistry, common sense,
“safety is your responsibility”

No matter how careful they are, people often make mistakes. An effective
Trust safety policy does not rely on people but relies on systems to reduce the
structures probability of accidents.
more than
people “I will be careful with chemicals” is a not an “idiot-proof” safety
precaution, chemical-resistant gloves are.

Everyone must be prepared to respond quickly and effectively in an

Respond to emergency. Become familiar with the work area, available exits, and
Emergencies safety equipment.
“training could save a life during an emergency”

Here are links for some important Safety related documents shared by
Safety
Related IISc: Safety Manual: https://olseh.iisc.ac.in/wp-
Documents content/uploads/2019/03/IIScSafetyManual_Ver1_01.pdf
Section: 4 Laboratory Experiments Skill Development

Ex. No: 1 Implementation of Knapsack Problem using


Date: Brute Force Technique

AIM

To implement knapsack problem using brute force technique.

ALGORITHM

Step - 1: Start the program.

Step - 2: Given N items of known weight w1, w2, … wn and profit p1, p2, … pn and a
knapsack of capacity W.

Step - 3: A simple solution is to consider all subsets of items and calculate the total
weight and value of all subsets.

Step - 4: Consider the only subsets whose total weight is smaller than W in order to
identify the feasible subsets.

Step - 5: From all feasible subsets, find the maximum value subset.

Step - 6: Stop the program


PROGRAM

#include<stdio.h>
struct good
{
int weight;
int value;
}
goods[50];
int n,bestValue,cv,cw,c,N,i=0;
int x[50],cx[50];
int knapstack(int i)
{
int k=0;
if(i>n-1)
{
if(bestValue<cv&&cw<=c)
{
for(k=0;k<n;k++)
{
x[k]=cx[k];
bestValue=cv;
}
}
return bestValue;
}
cw=cw+goods[i].weight;
cv=cv+goods[i].value;
cx[i]=1;
knapstack(i+1);
cw=cw-goods[i].weight;
cv=cv-goods[i].value;
cx[i]=0;
knapstack(i+1);
return bestValue;
}
int main()
{
int y;
printf("Please Enter the no.of items:");
scanf("%d",&n);
printf("Please enter the capacity of the packback:");
scanf("%d",&c);
printf("Please Enter the weight of the items in turn:");
for(i=0;i<n;i++)
{
scanf("%d",&goods[i].weight);
}
printf("Please Enter the values of the item in turn:");
for(i=0;i<n;i++)
{
scanf("%d",&goods[i].value);
}
y=knapstack(0);
printf("The Maximum value is %d",y);
printf("\n Optimal loading plan:");
for(i=0;i<n;i++)
{
printf("%d ",x[i]);
}
return 0;
}
SAMPLE OUTPUT

Please Enter the no.of items:3


Please enter the capacity of the packback:5
Please Enter the weight of the items in turn:1 3
1
2
Please Enter the values of the item in turn:4
6
7
The Maximum value is 13
optimal loading plan:0 1 1
VIVA QUESTIONS

1. What is the objective of the knapsack problem?

2. Time complexity of knapsack problem is?

3. You are given a knapsack that can carry a maximum weight of 60. There are 4 items with
weights {20, 30, 40, 70} and values {70, 80, 90, 200}. What is the maximum value of the items
you can carry using the knapsack?

RESULT

Thus the implementation of knapsack problem using brute force technique was verified
and executed successfully.

Observation by students: (what student able to?)

1.

MAX.
MARKS
CATEGORY MARKS
AWARDED
ALLOTED
LOGIC 30
CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION

TOTAL 100
Ex. No: 2 Implement Merge Sort and Quick Sort Algorithms and

Date: Compare the Time Complexity for Various of N Values

AIM

To implement merge sort algorithm and compare the time complexity for several of N
values.

ALGORITHM

Step - 1: Start the program.

Step - 2: Merge sort is a divide and conquer algorithm.

Step - 3: It divides the input array into two halves, calls itself for the two halves, and
then merges the two sorted halves.

middle = 1 + (last - first)/2

Step - 4: Find the middle index of the array and divide the array from the middle.

Step - 5: The mergesort() function is used for merging two halves.

mergesort(array, first, middle)

Step - 6: Call merge sort for the second half of the array.

mergesort(array, middle+1, last)

Step - 7: The merge() is a key process that sorts the A[l..m] and A[m+1..r] into two
sorted sub-arrays to merge the two sorted halves into a single sorted array.

Step - 8: Stop the program.


PROGRAM

#include<stdio.h>

#include<stdlib.h>

void mergesort(int a[],int low,int high)

int mid;

if(low<high)

mid=(low+high)/2;

mergesort(a,low,mid);

mergesort(a,mid+1,high);

merge(a,low,mid,high);

void merge(int a[],int low,int mid,int high)

int i, j, k;

int n1 = mid - low + 1;

int n2 = high - mid;

int temp1[n1], temp2[n2];

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

temp1[i] = a[low + i];

for (j = 0; j < n2; j++)

temp2[j] = a[mid + 1 + j];

i = 0;

j = 0;
k = low;

while (i < n1 && j < n2)

if (temp1[i] <= temp2[j])

a[k] = temp1[i];

i++;

else

a[k] = temp2[j];

j++;

k++;

while (i < n1)

a[k] = temp1[i];

i++;

k++;

while (j < n2)

a[k] = temp2[j];

j++;

k++;

}
}

int main()

int a[50],n,i=0;

printf("Enter the length of the array:");

scanf("%d",&n);

printf("Enter the Array elements:");

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

scanf("%d",&a[i]);

printf("\n Unsorted array:");

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

printf("%d ",a[i]);

mergesort(a,0,n-1);

printf("\n Sorted array :");

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

printf("%d ",a[i]);

}
SAMPLE OUTPUT

Enter the length of the array:8


Enter the Array elements:6
4
2
1
5
7
8
3
Unsorted array:6 4 2 1 5 7 8 3
Sorted array :1 2 3 4 5 6 7 8
VIVA QUESTIONS

1. Merge sort uses which of the following technique to implement sorting?

2. What is the worst case time complexity of merge sort?

RESULT

Thus the implementation of merge sort algorithm and comparison of the time
complexity for several of N values were executed successfully.
AIM

To implement quick sort algorithm and compare the time complexity for several of N
values.

ALGORITHM

Step - 1: Start the program.

Step - 2: Quick sort is a Divide and Conquer algorithm.

Step - 3: It picks an element as pivot and partitions the given array around the picked
pivot.

Step - 4: There are many different versions of Quicksort that pick pivot in different
ways.
Always pick first element as pivot. (Implemented below)

Step - 5: Given an array and an element x of array as pivot, put x at its correct position
in sorted array and put all smaller elements (smaller than x) before x, and put all greater
elements (greater than x) after x.

Step - 6: The left to right scan i starts with second element and skips over the elemetnt
smaller than pivot and stops if the element is greater than or equal to pivot.

Step - 7: The right to left scan j starts with last element and skips over the element larger
than pivot and stops if the element is smaller than or equal to pivot.

Step - 8: If scanning indices not crossed simply exchange A[i] and A[j] and resume the
scan by incrementing I and decrementing j.

Step - 9: If scanning indices crossed over and i > j then exchange pivot and A[j].

Step - 10: Stop the program.


PROGRAM

#include<stdio.h>
#include<stdlib.h>
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = (low - 1);
int j;
for (j = low; j < high; j++)
{
if (array[j] <= pivot)
{
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}
void quickSort(int array[], int low, int high)
{
if (low < high)
{
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void printArray(int array[], int size)
{
int i;
for (i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int data[50],n,i;
printf("Enter the size of the array : ");
scanf("%d",&n);
printf("Enter the array elements : ");
for (i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}
SAMPLE OUTPUT

[fystudent@a3fy16 ~]$ cc quick.c


[fystudent@a3fy16 ~]$ ./a.out
Enter the size of the array : 5
Enter the array elements : 8
4
9
2
3
Unsorted Array
84923
Sorted array in ascending order:
23489 ~
VIVA QUESTIONS

1. What is the worst case time complexity of a quick sort algorithm?

2. How many sub arrays does the quick sort algorithm divide the entire array into?

RESULT

Thus the implementation of quick sort algorithm and comparison of the time complexity
for several of N values were executed successfully.

Observation by students: (what student able to?)

1.

MAX. MARKS MARKS


CATEGORY
ALLOTED AWARDED
LOGIC 30

CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION

TOTAL 100
Ex. No: 3 Implementation of Warshall’s and Floyd’s Algorithm using

Date: Dynamic Programming Technique

AIM

To implement warshall‘s and floyd‘s algorithm using dynamic programming technique.

ALGORITHM

Step-1: Start the program.

Step-2: Specifically, the element in the ith row and jth column of matrix
is equal to 1 if and only if there exist a directed path of a positive length from the ith
vertex to the jth vertex with each intermediate vertex k.

Step-3: It is a weighted connected graph to calculate the length pf shortest path from
each vertex to all other vertices.

Step-4: D ←W
for k←1 to n do
for i ←1 to n do
for j ←1 to n do
D[i, j ]←min{D[i, j ], D[i, k]+ D[k, j]}
return D

Step-5: The element in row i and column j of the current distance matrix D (k−1) is
replaced by the sum of the elements in the same row i and the column k and in the same
column j and the row k if and only if the latter sum is smaller than its current value.

Step-6: Stop the program.


PROGRAM:

#include<stdio.h>
#define nV 4
#define INF 999
void printFloyd(int matrix[][nV])
{
for(int i=0;i<nV;i++)
{
for(int j=0;j<nV;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
}
void FloydWarshall(int graph[] [nV])
{
int matrix[nV][nV];
for(int i=0;i<nV;i++)
{
for(int j=0;j<nV;j++)
{
matrix[i][j]=graph[i][j];
}
}
for(int k=0;k<nV;k++)
{
for(int i=0;i<nV;i++)
{
for(int j=0;j<nV;j++)
{
if (matrix[i][j]> matrix[i][k] + matrix[k][j])
{
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
printFloyd(matrix);
printf("\n");
}
}
int main()
{
int graph[nV] [nV] = {{0,INF,3,INF},{2,0,INF,INF},{INF,7,0,1},{6,INF,INF,0}};
FloydWarshall(graph);
return 0;
}
SAMPLE OUTPUT

0 999 3 999
2 0 5 999
999 7 0 1
6 999 9 0

0 999 3 999
2 0 5 999
9 7 0 1
6 999 9 0

0 10 3 4
2 0 5 6
9 7 0 1
6 16 9 0

0 10 3 4

2 0 5 6
7 7 0 1
6 16 9 0
VIVA QUESTIONS

1. Floyd Warshall’s algorithm is used for solving

2. Complete the program.


n=rows[W]
D(0)=W
for k=1 to n
do for i=1 to n
do for j=1 to n
do ________________________________
return D(n)

3. What is the running time of the Floyd Warshall algorithm?

RESULT

Thus the implementation of warshall‘s and floyd‘s algorithm using dynamic


programming technique has been executed and verified successfully.

Observation by students: (what student able to?)

1.

MAX. MARKS MARKS


CATEGORY
ALLOTED AWARDED

LOGIC 30

CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION

TOTAL 100
Ex. No: 4 Implementation of Djikstra’s Algorithm using Greedy
Technique
Date:

AIM

To implement djikstra’s algorithm using greedy technique.

ALGORITHM

Step-1: Start the program.

Step-2: A tentative distance value is assigned to every node; this value is set to zero for
the initial node, and to infinity for all other nodes.

Step-3: All nodes unvisited are marked, and the initial node is set as current node.

Step-4: For the current/initial node, take into account all the unvisited nearby nodes,
and calculate their tentative distances.

Step-5: For all adjacent vertices of this vertex update distances.

Step-6: Make a comparison of the current assigned value and the newly calculated
tentative distance; assign the smaller value.

Step-7: A visited node is never to be checked again.

Step-8: Now check every adjacent vertex of V, if sum of distance of u and weight of
edge is else the update it.

Step-9: Find the unvisited node assigned with the smallest tentative distance value, and
this will be the new “current mode”.

Step-10: Once the algorithm is over, we can backtrack from the destination vertex to
the source vertex to find the path.

Step-11: Stop the program.


PROGRAM

#include<stdio.h> //header file


#include <stdlib.h> //header file
#define MAX 6
#define INFINITY 999999

void djikstra(int graph[MAX][MAX],int vertices,int start_node)


{
int cost[MAX][MAX],distance[MAX],path[MAX];
int visited[MAX],count=0,min_distance=0,next_node=0,i=0,j=0;
for(i=0;i<vertices;i++)
{
for(j=0;j<vertices;j++)
{
if(graph[i][j]==0)
{
cost[i][j]=INFINITY;
}
else
{
cost[i][j]=graph[i][j];
}
}
}
for(i=0;i<vertices;i++)
{
distance[i] = cost[start_node][i];
path[i] = start_node;
visited[i]=0;
}
distance[start_node]=0;
visited[start_node]=1;
count=1;
while(count<vertices-1)
{
min_distance = INFINITY;
for(i=0;i<vertices;i++)
{
if(distance[i] < min_distance && !visited[i])
{
min_distance = distance[i];
next_node=i;
}
}
visited[next_node]=1;
for(i=0;i<vertices;i++)
{
if(!visited[i])
{
if(min_distance+cost[next_node][i]< distance[i])
{
distance[i]=min_distance+cost[next_node][i];
path[i]=next_node;
}
}
}
count++;
}
for(i=0;i<vertices;i++)
{
if(i!=start_node)
{
printf("\n Distance Of Node %d = %d",i,distance[i]);
printf("\n Path =%d",i);
j=i;
do
{
j = path[j];
printf("<--------%d",j);
}while(j!=start_node);
printf("\n");
}
}
}

int main()
{
int i=0,j=0;
int vertices=0,start_node=0;
//int graph[MAX][MAX] =
{{0,10,0,30,100},{10,0,50,0,0},{0,50,0,20,10},{30,0,20,0,60},{100,0,10,60,0}};
int graph[MAX][MAX] =
{{0,3,0,7,0,10},{3,0,4,2,0,0},{0,4,0,5,6,0},{7,2,5,0,4,2},{0,0,6,4,0,1},{10,0,0,2,1,0}};
printf("\n Enter The Number Of Vertices :");
scanf("%d",&vertices);
printf("\n Enter The Starting Node : ");
scanf("%d",&start_node);
djikstra(graph,vertices,start_node);
return 0;
}
SAMPLE OUTPUT

[fystudent@a3fy06 ~]$ cc djikstras.c


[fystudent@a3fy06 ~]$ ./a.out
Enter The Number Of Vertices :6
Enter The Starting Node : 0
Distance Of Node 1 = 3
Path =1<--------0
Distance Of Node 2 = 7
Path =2<--------1<--------0
Distance Of Node 3 = 5
Path =3<--------1<--------0
Distance Of Node 4 = 8
Path =4<--------5<--------3<--------1<--------0
Distance Of Node 5 = 7
Path =5<--------3<--------1<--------0
[fystudent@a3fy06 ~]$
VIVA QUESTIONS

1. Which of the following algorithms is the best approach for solving single source shortest
path?

2. What is the time complexity of Djikstra’s algorithm?

3. If b is the source vertex, what is the minimum cost to reach f vertex?

RESULT

Thus the implementation of djikstra’s algorithm using greedy technique has been
executed and verified successfully.

Observation by students: (what student able to?)

1.

MAX. MARKS MARKS


CATEGORY
ALLOTED AWARDED

LOGIC 30

CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION
TOTAL 100
Ex. No: 5 Implementation of Stable Marriage Problem using
Iterative Improvement Technique
Date:

AIM

To write a program to implement stable marriage problem using iterative improvement


technique.

ALGORITHM

Step-1: Start the program.

Step-2: Consider a set Y = {m1, m2, . ., mn} of n men and a set X = {w1, w2, . . , wn}
of n women.

Step-3: Each man has a preference list ordering the women as potential marriage
partners with no ties allowed. Similarly, each woman has a preference list of the men,
also with no ties.

Step-4: Start with all the men and women being free.

Step-5: While there are free men, arbitrarily select one of them and do the following:

Step-6: Proposal - The selected free man m proposes to w, the next woman on his
preference list (who is the highest-ranked woman who has not rejected him before).

Step-7: Response - If w is free, she accepts the proposal to be matched with m.


If she is not free, she compares m with her current mate.

Step-8: If she prefers m to him, she accepts m’s proposal, making her former mate free,
otherwise, she simply rejects m’s proposal, leaving m free.

Step-9: Return the set of n matched pairs.

Step-10: Stop the program.


PROGRAM

#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
#define N 4
bool wPrefersM1OverM(int prefer[2*N][N], int w, int m, int m1)
{
int i;
// Check if w prefers m over her current engagement m1
for (i = 0; i < N; i++)
{
// If m1 comes before m in list of w, then w prefers her
// current engagement, don't do anything
if (prefer[w][i] == m1)
return true;
// If m comes before m1 in w's list, then free her current
// engagement and engage her with m
if (prefer[w][i] == m)
return false;
}
}
// Prints stable matching for N boys and N girls.
// Boys are numbered as 0 to N-1. Girls are numbered
// as N to 2N-1.
void stableMarriage(int prefer[2*N][N])
{
int wPartner[N];
int mFree[N],i;
for(i=0;i<N;i++)
{
wPartner[i]=-1;
mFree[i]=false;
}
int freeCount = N;
while (freeCount > 0)
{
// Pick the first free man (we could pick any)
int m,i;
for (m = 0; m < N; m++)
if (mFree[m] == false)
break;
for (i = 0; i < N && mFree[m] == false; i++)
{
int w = prefer[m][i];
if (wPartner[w-N] == -1)
{
wPartner[w-N] = m;
mFree[m] = true;
freeCount--;
}
else // If w is not free
{
// Find current engagement of w
int m1 = wPartner[w-N];
// If w prefers m over her current engagement m1,
// then break the engagement between w and m1 and
// engage m with w.
if (wPrefersM1OverM(prefer, w, m, m1) == false)
{
wPartner[w-N] = m;
mFree[m] = true;
mFree[m1] = false;
}
} // End of Else
} // End of the for loop that goes to all women in m's list
} // End of main while loop
printf("Woman Man\n");
for (i = 0; i < N; i++)
printf("%d \t %d\n ",i+N,wPartner[i]);
}
int main()
{
int i;
int prefer[2*N][N] =
{{7,5,6,4},{5,4,6,7},{4,5,6,7},{4,5,6,7},{0,1,2,3},{0,1,2,3},{0,1,2,3},{0,1,2,3}};
stableMarriage(prefer);
return 0;
}
SAMPLE OUTPUT

[student@a2it12 ~]$ cc stable.c


[student@a2it12 ~]$ ./a.out
Woman Man

4 2

5 1

6 3

7 0
[student@a2it12 ~]$
VIVA QUESTIONS

1. When a free man proposes to an available woman, which of the following happens?

2. What happens when a free man approaches a married woman?

3. Consider the following ranking matrix. Assume that M1 and W2 are married. Now, M2
approaches W2. Which of the following happens?

RESULT

Thus the program to implement stable marriage problem using iterative improvement
technique has been verified and executed successfully.

Observation by students: (what student able to?)

1.

MAX. MARKS MARKS


CATEGORY
ALLOTED AWARDED

LOGIC 30

CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION
TOTAL 100
Ex. No: 6 Implementation of N-Queens Problem using
Backtracking Technique
Date:

AIM

To write a program to implement n-queens problem using backtracking technique.

ALGORITHM

Step-1: Start the program.

Step-2: The problem is to place n queens on an n × n chessboard so that no two queens


attack each other by being in the same row or in the same column or on the same
diagonal.

Step-3: We start with the empty board and then place queen 1 in the first possible
position of its row, which is in column 1 of row 1.

Step-4: The four queens has to be placed in its own row, all we need to do is to assign
a column for each queen on the board.

Step-5: Start in the leftmost column. If all queens are placed return true.

Step-6: Try all rows in the current column.

a) If the queen can be placed safely in this row then mark this [row, column] as
part of the solution and recursively check if placing queen here leads to a
solution.
b) If placing the queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then unmark this [row, column]
Backtrack and go to step (a) to try other rows.
d) If all rows have been tried and nothing worked, return false to trigger
backtracking.

Step-7: Stop the program.


PROGRAM

#include<stdio.h> //header file


#include<stdlib.h> //header file
#define N 8
int NQueens(int board[N][N], int column)
{
int i = 0;
if(column >= N)
{
return 1;
}
for(i=0;i<N;i++)
{
if(isSafe(board,i,column))
{
board[i][column]=1;
//printf("QUEEN = %d %d \t \n",i,column);
if(NQueens(board,column+1))
{
return 1;
}
board[i][column]=0;
}
}
return 0;
}
int isSafe(int board[N][N],int row,int column)
{
int i=0, j=0;
for(i=0;i<column;i++)
{
if(board[row][i])
{
return 0;
}
}
for(i=row,j=column; i>=0 && j>=0; i--,j--)
{
if(board[i][j])
{
return 0;
}
}
for(i=row,j=column; j>=0 && i<N; i++,j--)
{
if(board[i][j])
{
return 0;
}
}
return 1;
}
void display(int board[N][N])
{
int i=0,j=0;
printf("\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
printf("%d \t",board[i][j]);
}
printf("\n");
}
}
int main() //main function
{
int result=0;
int i=0,j=0; //variable declaration
int board[50][50];
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
board[i][j]=0;
}
}
result = NQueens(board,0);
if(result == 0) //if condition
{
printf("\n Solution Does Not Exist");
}
else //else condition
{
display(board);
}
return 0;
}
SAMPLE OUTPUT

[student@a2it12 ~]$ cc eight_queen.c


[student@a2it12 ~]$ ./a.out
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
VIVA QUESTIONS

1. Backtracking algorithm is implemented by constructing a tree of choices called as?

2. In how many directions do queens attack each other?

3. Which of the following methods can be used to solve n-queen’s problem?

4. How many possible solutions exist for an 8-queen problem?

RESULT

Thus the program to implement n-queens problem using backtracking technique has
been verified and executed successfully.

Observation by students: (what student able to?)

1.

MAX. MARKS MARKS


CATEGORY
ALLOTED AWARDED

LOGIC 30

CODE DESIGN 30

VIVA-VOCE 20

RECORD
20
SUBMISSION
TOTAL 100

You might also like