You are on page 1of 74

Institute of Technology & Management Universe

Dhanora Tank Road, Paldi Village, Halol Highway,


Near Jarod, Vadodara Dist, Gujarat, INDIA-391510
(Approved by AICTE, New Delhi, and Affiliated to Gujarat Technological University, Ahmadabad)

FACULTY LABORATORY MANUAL

For

V Semester CSE

Session: 2017-2018

Analysis and Design of Algorithm

Subject Code: 2150703

Prepared by:

Anuj Kumar Jain,

Assistant Professor

Department of Computer Science & Engineering

June -2017

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Institute of Technology & Management Universe
Dhanora Tank Road, Paldi Village, Halol Highway,
Near Jarod, Vadodara Dist, Gujarat, INDIA-391510
(Approved by AICTE, New Delhi, and Affiliated to Gujarat Technological University, Ahmadabad)

STUDENT CERTIFICATE

This is to certify Mr.\ Miss ................................................................ student of

Computer Engineering GTU Enrollment No. ............................................. has

satisfactorily completed his/her term-work ................................... in Analysis and

Design of Algorithm for term ending in.........................2017.

Date:

Place:

Signature of Faculty Signature of Faculty

(..............................................) (..............................................)

Date Date

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
1. Vision & Mission of ITMU
Vision
To develop the institute into a centre of excellence in education, research, training and
consultancy to the extent that it becomes a significant player in the technical and overall
development of the country.
Mission
To meet the global need of competent and dedicated professionals. To undertake research &
development, consultancy & extension activities which are relevant to the needs of mankind. To
serve the community by interaction on technical, scientific and other aspects of development.
Values
Humanity and ethics blended with sincerity, integrity and accountability. Productive delivery
supported by healthy competition. Efficiency and dynamism coupled with sensitivity. To nurture
innovation and ability to think differently with rational creativity. Appreciation of sustainable
socio- cultural values and to feel proud to be a good professional contributing to the betterment
of the Mankind and Mother Earth.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
2. Vision & Mission of CSE Department

Vision
To develop the Computer Science & Engineering Department into an excellent center of
learning, research, consultancy and training.

Mission
PO1: To produce professionally brilliant, rounded and motivated Engineers in the field of
Computer Science & Engineering.
PO2: To undertake developmental research, consultancy and technical interaction with
industry

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
3. PEO (Programme Educational Objectives)

1) The CSE program will prepare the graduates for Excellent professional and technical
careers.
2) The CSE program will prepare the graduates for adapting themselves with constantly
changing technology with the ability of continuous learning.
3) The CSE program will prepare the graduates to effectively communicate and to
understand professional, ethical and social responsibilities.
4) The CSE program will prepare graduates to work as a part of team on multidisciplinary
projects.
5) The CSE program will prepare graduates to gain the ability to identify, analyze,
formulate, and solve engineering problems.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
4. PO (Programme Outcome)
a) Ability to apply knowledge of mathematics, science and engineering in Computer Sc. &
Engineering.
b) Ability to design and conduct experiments, analyze and interpret data.
c) Graduates will have strong fundamental concepts on core Computer Science &
Engineering subjects.
d) Ability to design develops, test and debug the software.
e) Ability to deploy, analyzes, troubleshoot, maintain, manage and secure the complex
computer networks.
f) Ability to work cooperatively, creatively and responsibly in a multi-disciplinary team.
g) Ability to respond positively to the accepted norms of professional and ethical
responsibility.
h) Ability to communicate effectively by oral, written and various presentation skills using
IT tools
i) Ability to respond effectively to the global, societal and environmental concerns in
developing computer engineering solutions.
j) Ability to acquire, understand and apply information in the process of lifelong learning.
k) Ability to appreciate contemporary issues in Computer Science & Engineering.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
5. Lab Syllabus
GUJARAT TECHNOLOGICAL UNIVERSITY
B.E. SEMESTER: V
COMPUTER SCIENCE & ENGINEERING

Subject Name: Analysis and Design of Algorithms Subject Code: 2150703


Evaluation Scheme

List of Experiments:
1. Implementation and Time analysis of sorting algorithms. Bubble sort, Selection sort, Insertion sort,
Merge sort and Quicksort
2. Implementation and Time analysis of linear and binary search algorithm.
3. Implementation of max-heap sort algorithm
4. Implementation and Time analysis of factorial program using iterative and recursive method
5. Implementation of a knapsack problem using dynamic programming.
6. Implementation of chain matrix multiplication using dynamic programming.
7. Implementation of making a change problem using dynamic programming
8. Implementation of a knapsack problem using greedy algorithm
9. Implementation of Graph and Searching (DFS and BFS).
10. Implement prims algorithm
11. Implement kruskals algorithm.
12. Implement LCS problem.

Design based Problems (DP)/Open Ended Problem:


1. From the given string find maximum size possible palindrome sequence
2. Explore the application of Knapsack in human resource selection and courier loading system using
dynamic programming and greedy algorithm
3. BRTS route design, considering traffic, traffic on road, and benefits

ACTIVE LEARNING ASSIGNMENTS: Preparation of power-point slides, which include videos,


animations, pictures, graphics for better understanding theory and practical work The faculty will
allocate chapters/ parts of chapters to groups of students so that the entire syllabus to be covered. The
power-point slides should be put up on the web-site of the College/ Institute, along with the names of the
students of the group, the name of the faculty, Department and College on the first slide. The best three
works should submit to GTU.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
6. List of Experiment

S. No. Date of Title Page Grade Signature


Experiment No.
Write a C program to Implementation and
Time analysis of sorting algorithms.
1
Bubble sort, Selection sort, Insertion sort,
Merge sort and Quicksort
Write a C program to Implementation and
2 Time analysis of linear and binary search
algorithm.
Write a C program to Implementation of
3
max-heap sort algorithm
Write a C program to Implementation and
4 Time analysis of factorial program using
iterative and recursive method
Write a C program to Implementation of a
5 knapsack problem using dynamic
programming.
Write a C program to Implementation of
6 chain matrix multiplication using
dynamic programming.
Write a C program to Implementation of
7 making a change problem using dynamic
programming
Write a C program to Implementation of a
8
knapsack problem using greedy algorithm
Write a C program to Implementation of
9-a
DFS .
Write a C program to Implementation of
9-b
BFS
Write a C program to Implement prims
10
algorithm
Write a C program to Implement
11
kruskals algorithm.
Write a C program to Implement LCS
12
problem.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
7. Lab Plan
Batch - A
S. No List of Experiment Batch A-1 Batch A-2 Batch A-3
Performe Back Log Performed Back Log Performed Back Log
d Date Date Date Date Date Date
1 Implementation and Time analysis of sorting algorithms. Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort
2 Implementation and Time analysis of linear and binary search
algorithm.
3 Implementation of max-heap sort algorithm

4 Implementation and Time analysis of factorial program using iterative


and recursive method
5 Implementation of a knapsack problem using dynamic programming.

6 Implementation of chain matrix multiplication using dynamic


programming.
7 Implementation of making a change problem using dynamic
programming
8 Implementation of a knapsack problem using greedy algorithm

9 Implementation of DFS .

10 Implementation of BFS

11 Implement prims algorithm

11-1 Implement kruskals algorithm.

12 to Implement LCS problem.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Batch-B
S. No List of Experiment Batch B-1 Batch B-2 Batch B-3
Performe Back Log Performed Back Log Performed Back Log
d Date Date Date Date Date Date
1 Implementation and Time analysis of sorting algorithms. Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort
2 Implementation and Time analysis of linear and binary search
algorithm.
3 Implementation of max-heap sort algorithm

4 Implementation and Time analysis of factorial program using iterative


and recursive method
5 Implementation of a knapsack problem using dynamic programming.

6 Implementation of chain matrix multiplication using dynamic


programming.
7 Implementation of making a change problem using dynamic
programming
8 Implementation of a knapsack problem using greedy algorithm

9 Implementation of DFS .

10 Implementation of BFS

11 Implement prims algorithm

11-1 Implement kruskals algorithm.

12 to Implement LCS problem.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
8 ALA Topics
Batch -A
Sr. ALA Topic
Enroll. No. Name of the Student
No.
1 150950107001 VAIDYA ADITYA HIRENKUMAR Basics of Algorithms
2 150950107002 RANADE ADVAIT G Asymptotic Notations
3 150950107003 CHARMI AGRAWAL Amortized analysis
Analyzing control statement,
4 150950107004 AGRAWAL DRASHTI KAMLESH
Loop invariant
5 150950107005 ALFERD ALVES CHRISTO Bubble sort, Selection sort
6 150950107007 PRAJAPATI AYUSHI YOGESH Insertion sort, Shell sort
BORAH BAHNIMAN HOREN Heap sort
7 150950107008
CHANDRA
8 150950107009 PATEL BANSARI RAJESHBHAI Bucket sort, Radix sort
9 150950107010 BARBHAYA BHAVYA MANISH Counting sort
10 150950107011 BHAGAT RAHI KUMAR Recurrence &
11 150950107012 BHANDHARI NAMAS SANJIV Substitution method
Recurrence and Iteration
12 150950107014 BHATT VALAY AVINASH
methods to solve recurrence
13 150950107015 BRAHMBHATT YASH RAJENDRA Master Method with Proof
Recurrence and Recursive tree
15 150950107017 CHOKSI JANKI NIKUNJ
methods to solve recurrence
divide and conquer algorithm -
16 150950107018 CHOYAL KETAN RAJPAL
Binary Search
18 150950107020 DAVE RICHA RAJENDRA Merge Sort
19 150950107021 DESAI ANERI DIVYANG Quick Sort
DOLIA DEVANSHI Matrix Multiplication,
20 150950107022 Exponential
DHARMENDRASINH
Dynamic Programming
21 150950107023 DHAMDHERE SHALAKA SUDHIR Calculating the Binomial
Coefficient
22 150950107024 DHOPTE ABHIRAJ PRATAP Making Change Problem,
23 150950107025 SHAH DHRUMIL SHITALBHAI Assembly Line-Scheduling,
24 150950107026 DIALANI DIMPLE JAIRAM Knapsack problem
25 150950107027 DIWAKAR SHUBHAM MANOHAR All Points Shortest path,
Greedy Algorithm- Activity
26 150950107028 DOSHI RISHI DEEPAKKUMAR selection problem
Minimum Spanning trees
27 150950107029 GANDHI HELLY DEVESH (Kruskals algorithm, Prims
algorithm),
28 150950107030 GANDHI PARTH VIJAYKUMAR Depth First Search
29 150950107031 GONSALVES AARON DOMINIC Breath First Search
GOSWAMI PRIYANK Topological sort
30 150950107032
BRIJESHGIRI
31 150950107034 PATEL HARSH AJAYKUMAR Connected components
32 150950107035 BHUVA HARSH PRAVINBHAI The Eight queens problem , ,
Travelling Salesman problem,
33 150950107036 MODI HIMANI BHARATKUMAR Minimax principle
34 150950107037 JADAV PRIYAL PRAVINBHAI Knapsack problem

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
JAMBEKAR VISHAKAHA Shortest paths
35 150950107038
UNMESH
36 150950107039 PATEL JHANVI JIGNESHKUMAR Fractional Knapsack Problem,
37 150950107040 JIVANI SIMRAN YUSUFBHAI Job Scheduling Problem
38 150950107041 JOSHI HETA ALKESH Huffman code
KAYADAWALA MOIZ The naive string matching
40 150950107043 algorithm, , ,
FAKHRIBHAI
The Knuth-Morris-Pratt
41 150950107044 KHATRI KAMAL RAMKRISHNA algorithm.
String Matching with finite
42 150950107045 KOTWAL KHUSHBU DIPAKBHAI automata
43 150950107046 KUKREJA JUGAL GAJENDRAPAL The Rabin-Karp algorithm
The class P and NP, Polynomial
44 150950107047 PATEL KUNJ RAKESH reduction, NP- Completeness
Problem, NP-Hard Problems
SHARMA KUSHAGR Approximation algorithm
45 150950107048
AVDESHKUMAR
46 150950107049 LUHAR MEET JAGDIP Hamiltonian problem,
47 150950107050 PATEL MAITRI NITINBHAI Travelling Salesman problem
Dynamic Programming
MEHTA HARIOM
48 150950107051 Calculating the Binomial
HIMANSHUBHAI Coefficient
49 150950107052 MEHTA ZANKHIT MUKESH Making Change Problem,
50 150950107053 PUROHIT MEHUL JITENDRA Assembly Line-Scheduling,
51 150950107054 SHAH MIRAL MEHUL Knapsack problem
52 150950107055 MODI HARSH NAYANKUMAR All Points Shortest path,
MOKANI PRASHANT Greedy Algorithm- Activity
53 150950107056 selection problem
AMRISHBHAI
Minimum Spanning trees
54 150950107057 NAIK HARSHAL ROHITBHAI (Kruskals algorithm, Prims
algorithm),
55 150950107058 SINHA NAMAN SANJEEB Depth First Search
56 150950107059 PATEL NEEL AKASH Breath First Search
57 150950107060 NINAWE RUCHI PRAKASH Topological sort
58 150950107061 TIWARI PALAK KISHOR Connected components
59 150954107001 RAHUL JALINDAR SONEWANE The Eight queens problem , ,
Travelling Salesman problem,
60 160953107001 KAVINB.ANGHAN
Minimax principle
61 160953107002 KEVIN B .ANGHAN Knapsack problem
62 160953107006 KUSH M .DAVE Shortest paths
63 160953107007 RUDRA K. DAVE Fractional Knapsack Problem,
64 160953107008 AAKURTI DESAI Job Scheduling Problem
65 160953107009 SHRIPAD S.JOSHI Huffman code
66 160953107015 VIDHI D .PATEL Insertion sort, Shell sort

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Batch -B
Sr. ALA Topic
Enroll. No. Name of the Student
No.
1 150950107064 PARAM TRUSHA PRASHANT Basics of Algorithms
PAREKH VIDHISHA Asymptotic Notations
2
150950107065 UMESHKUMAR
3 150950107066 PARIKH ANUJ HEMANTKUMAR Amortized analysis
Analyzing control statement,
4 150950107067 PARIKH NISARG MRUNAL Loop invariant
5 150950107068 DESAI PARTH RAJESHBHAI Bubble sort, Selection sort
6 150950107070 PATEL DHARMIK MITESH Insertion sort, Shell sort
7 150950107071 PATEL DHRUV DILIPBHAI Heap sort
8 150950107072 PATEL DHRUV VASANT Bucket sort, Radix sort
9 150950107073 PATEL HARDI SURESHBHAI Counting sort
10 150950107074 PATEL KARAN MANIOJBHAI Recurrence &
11 150950107076 PATEL NIKET CHIRAG Substitution method
Recurrence and Iteration
12 150950107077 PATEL NIRMAL UPENDRABHAI methods to solve recurrence
PATEL RITUKUMARI Master Method with Proof
13
150950107078 VIRENDRABHAI
Recurrence and Recursive tree
15 150950107079 PATEL SNEH KAMLESHKUMAR methods to solve recurrence
PATEL VAIBHAV divide and conquer algorithm -
16 Binary Search
150950107081 MAHENDRABHAI
18 150950107082 PATIL BHUMIKA ARUNRAO Merge Sort
19 150950107083 SATA PRANSHI Quick Sort
Matrix Multiplication,
20 150950107084 PUROHIT PRADIP SHIVLAL Exponential
Dynamic Programming
21 Calculating the Binomial
150950107085 PATEL RAJ KIRANKUMAR Coefficient
22 150950107086 RASHMI ANILKUMAR Making Change Problem,
23 150950107087 RAVAL VANDAN Assembly Line-Scheduling,
24 150950107088 PANDYA RUDRA NIKHIL Knapsack problem
SANGLOD PARTHIVSINH All Points Shortest path,
25
150950107089 JAYDEEPSINH
Greedy Algorithm- Activity
26 150950107091 SHAH AKSHAT VIPUL selection problem
Minimum Spanning trees
27 (Kruskals algorithm, Prims
150950107092 SHAH DHRUV KETANKUMAR algorithm),
28 150950107093 SHAH JENISHA JAYDUTT Depth First Search
29 150950107094 SHAH KALP Breath First Search
SHAH KHUSHBOO Topological sort
30
150950107095 CHANDRAKANT
31 150950107096 SHAH NEEL SANJAY Connected components
32 150950107097 SHAH NISARG BHAGYESH The Eight queens problem , ,
Travelling Salesman problem,
33 150950107098 SHAH NUPUR DHARMESHBHAI Minimax principle
34 150950107099 SHAH PARTH DIVYESH Knapsack problem

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
35 150950107100 SHAH RIKEN JAINESHBHAI Shortest paths
36 150950107101 SHAH SAGAR SANDIPKUMAR Fractional Knapsack Problem,
37 150950107103 SHAH SAMYAK YOGESH Job Scheduling Problem
38 150950107104 SHAH SHLOK Huffman code
The naive string matching
40 150950107105 SHAH VRAJ MANOJ algorithm, , ,
The Knuth-Morris-Pratt
41 150950107106 SHAHERAWALA HARSH algorithm.
String Matching with finite
42 150950107107 SHARMA HARSHDA ANIL automata
43 150950107108 SHARMA SHIVANI NILESHBHAI The Rabin-Karp algorithm
The class P and NP, Polynomial
44 reduction, NP- Completeness
150950107109 SHIVNANI PARSHAV VINOD Problem, NP-Hard Problems
45 150950107110 PATEL SHRADDHA YOGESHBHAI Approximation algorithm
RATHOD SHRESHTH Hamiltonian problem,
46
150950107111 JASHVANTKUMAR
47 150950107112 SHUKLA HELLY RAJESHKUMAR Travelling Salesman problem
Dynamic Programming
48 Calculating the Binomial
150950107113 SONI RIYA HITESHKUMAR Coefficient
49 150950107114 JADAV STEVE SURESHKKUMAR Making Change Problem,
SUKHADIYA RACHANA Assembly Line-Scheduling,
50
150950107115 PARESHBHAI
51 150950107116 SENJALIYA TANVI AMBABHAI Knapsack problem
52 150950107117 TAPKIR POOJA All Points Shortest path,
Greedy Algorithm- Activity
53 150950107118 THAKAR SHREY NILESHKUMAR selection problem
Minimum Spanning trees
54 (Kruskals algorithm, Prims
150950107119 THAKKAR RESHMA MANISH algorithm),
55 150950107120 TRIVEDI AAYUSHI SNEHAL Depth First Search
56 150950107121 VAMJA DEVVRAT RAJESHBHAI Breath First Search
VANJANI SHUBHANG Topological sort
57
150950107122 BHARATKUMAR
58 150950107123 FOJDAR VISHAL SHIVKUMAR Connected components
59 160953107003 BHAVSAR MEET ASHOKKUMAR The Eight queens problem , ,
CHAVDA URVASHIBEN Travelling Salesman problem,
60 Minimax principle
160953107005 JASHWANTBHAI
LADANI RIDDHI Knapsack problem
61
160953107010 CHANDRAKANTBHAI
62 160953107011 NIGAM SHEFALI AJAY Shortest paths
63 160953107012 NIKUMBH SAYLI MAHESHBHAI Fractional Knapsack Problem,
64 160953107013 PARMAR AMITA ARVINDBHAI Job Scheduling Problem
65 160953107014 PARMAR PREMLAL SANTLAL Huffman code

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
9. Batch Wise student List
Batch -B
BATCH-B1 Batch B2 Batch B3
Sr.
Sr. Sr.
Enrollment Name Enrollment Name No Enrollment Name
No. No.
.
1 150950107086 Rashmi Anilkumar 1 150950107109 Shivnani Parshav Vinod 1 150950107091 Shah Akshat Vipul
2 150950107078 Patel Ritukumari Virendrabhai 2 150950107120 Trivedi Aayushi Snehal 2 150950107094 Shah Kalp
Rathod Shreshth
3 150950107119 Thakkar Reshma Manish 3 150950107111 3 150950107074 Patel Karan Maniojbhai
Jashvantkumar
4 150950107114 Jadav Steve Sureshkkumar 4 150950107081 Patel Vaibhav Mahendrabhai 4 150950107093 Shah Jenisha Jaydutt
5 150950107113 Soni Riya Hiteshkumar 5 150950107106 Shaherawala Harsh 5 150950107105 Shah Vraj Manoj
6 150950107073 Patel Hardi Sureshbhai 6 150950107110 Patel Shraddha Yogeshbhai 6 150950107085 Patel Raj Kirankumar
Vanjani Shubhang
7 150950107116 Senjaliya Tanvi Ambabhai 7 150950107122 7 150950107123 Fojdar Vishal Shivkumar
Bharatkumar
8 150950107108 Sharma Shivani Nileshbhai 8 150950107064 Param Trusha Prashant 8 150950107077 Patel Nirmal Upendrabhai
9 150950107098 Shah Nupur Dharmeshbhai 9 150950107117 Tapkir Pooja 9 150950107097 Shah Nisarg Bhagyesh
10 150950107082 Patil Bhumika Arunrao 10 150950107071 Patel Dhruv Dilipbhai 10 160953107018 Trivedi Rudhra Kamlesh
11 150950107088 Pandya Rudra Nikhil 11 150950107076 Patel Niket Chirag 11 150950107096 Shah Neel Sanjay
12 150950107115 Sukhadiya Rachana Pareshbhai 12 150950107100 Shah Riken Jaineshbhai 12 160953107010 Ladani Riddhi Chandrakantbhai
13 150950107083 Sata Pranshi 13 150950107104 Shah Shlok 13 160953107013 Parmar Amita Arvindbhai
Suthar Manankumar
14 150950107070 Patel Dharmik Mitesh 14 160953107017 14 150950107072 Patel Dhruv Vasant
Jitendrakumar
15 160953107012 Nikumbh Sayli Maheshbhai 15 150950107068 Desai Parth Rajeshbhai 15 160953107003 Bhavsar Meet Ashokkumar
Sanglod Parthivsinh
16 150950107065 Parekh Vidhisha Umeshkumar 16 150950107089 Jaydeepsinh 16 150950107118 Thakar Shrey Nileshkumar
17 150950107095 Shah Khushboo Chandrakant 17 150950107099 Shah Parth Divyesh 17 160953107016 Shah Princy Vrajeshkumar
Chavda Urvashiben
18 150950107107 Sharma Harshda Anil 18 150950107101 Shah Sagar Sandipkumar 18 160953107005 Jashwantbhai
19 150950107112 Shukla Helly Rajeshkumar 19 150950107079 Patel Sneh Kamleshkumar 19 160953107011 Nigam Shefali Ajay
20 150950107066 Parikh Anuj Hemantkumar 20 160953107014 Parmar Premlal Santlal 20 150950107084 Purohit Pradip Shivlal
21 150950107103 Shah Samyak Yogesh 21 150950107121 Vamja Devvrat Rajeshbhai 21 150950107067 Parikh Nisarg Mrunal
22 150950107092 Shah Dhruv Ketankumar 22 150950107087 Raval Vandan

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Batch - A
Batch-A1 Batch A2 Batch A3
Sr
Sr. Sr. .
Enrollment Name Enrollment Name Enrollment Name
No. No. N
o.
1 150950107037 Jadav Priyal Pravinbhai 1 150950107029 Gandhi Helly 1 150950107014 Bhatt Valay Avinash
Kotwal Khushbu Dipakbhai Himani Modi Kushagar Sharma
2 150950107045 2 150950107036 2 150950107048
3 150950107038 Jambekar Vishakha 3 150950107041 Joshi Heta Alkesh 3 150950107027 Diwakar Shubham Manohar
4 150950107040 Jivani Simran Yusufbhai 4 150950107049 Luhar Meet Jagdip 4 150950107024 Dhopte Abhiraj Pratap
5 150950107044 Khatri Kamal Ramkrishna 5 150950107009 Bansari Patel 5 150950107053 Mehul Purohit
6 150950107039 Jhanvi J Patel 6 150950107060 Ninawe Ruchi Prakash 6 160953107008 Aakurti Desai
7 150950107021 Desai Aneri Divyang 7 150950107020 Dave Richa Rajendra 7 150950107043 Kaydawala Moiz Fakhribhai
8 150950107012 Bhandari Namas Sanjiv 8 150950107017 Choxi Janki Nikunj 8 160953107006 Kush M .Dave
9 150950107026 Dialani Dimple Jairam 9 150950107058 Naman Sinha 9 150950107001 Aditya Hirenkumar Vaidya
10 150950107023 Dhamdhere Shalaka Sudhir 10 160953107002 Kevin B .Anghan 10 150950107015 Brahmbhatt Yash Rajendra
11 150950107031 Gonsalves Aaron Dominic 11 150950107004 Agrawal Drashti Kamlesh 11 150950107047 Kunj Rakeshkumar Patel
12 150950107056 Mokani Prashant Amrishbhai 12 150950107035 Harsh Pravinbhai Bhuva 12 160953107007 Rudra K. Dave
13 150950107046 Kukreja Jugal Gajendrapal 13 150950107051 Mehta Hariom 13 150950107025 Dhrumil Shah
14 150950107030 Gandhi Parth Vijaykumar 14 150950107018 Choyal Ketan Rajpal 14 150950107002 Advait G Ranade
15 150950107054 Shah Miral Mehulbhai 15 160953107015 Vidhi D .Patel 15 150950107011 Bhagat Rahikumar Ramkrishna
16 160953107001 Kavinb.Anghan 16 150950107055 Modi Harsh Nayankumar 16 150950107005 Alves Christo Alfred
17 150950107022 Devanshi 17 150954107001 Rahul Jalindar Sonewane 17 160953107009 Shripad S.Joshi
Barbhaya Bhavya
Maitri Patel Bahniman Borah
18 150950107050 18 150950107008 18 150950107010 Manishkumar
19 150950107003 Agrawal Charmi Dushyant 19 150950107034 Harsh Patel 19 150950107061 Palak
20 150950107057 Naik Harshal Rohitbhai 20 150950107052 Mehta Zankhit Mukesh
21 150950107032 Goswami Priyank Brijeshgiri 21 150950107059 Neel Patel
22 150950107028 Doshi Rishi Deepakkumar 22 150950107007 Ayushi Prajapati

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 1
Aim: Write a C program to implementation and Time analysis of sorting algorithms.
Bubble sort, Selection sort, Insertion sort, Merge sort and Quick sort

Theory:
Selection Sort: The idea of selection sort is rather simple: we repeatedly find the next largest (or
smallest) element in the array and move it to its final position in the sorted array. Assume that we wish to
sort the array in increasing order, i.e. the smallest element at the beginning of the array and the largest
element at the end. We begin by selecting the largest element and moving it to the highest index position.
We can do this by swapping the element at the highest index and the largest element. We then reduce
the effective size of the array by one element and repeat the process on the smaller (sub)array. The
process stops when the effective size of the array becomes 1 (an array of 1 element is already sorted).
For example, consider the following array, shown with array elements in sequence separated by commas:
63, 75, 90, 12, 27
The leftmost element is at index zero, and the rightmost element is at the highest array index, in our case,
4 (the effective size of our array is 5). The largest element in this effective array (index 0-4) is at index 2.
We have shown the largest element and the one at the highest index in bold. We then swap the element at
index 2 with that at index 4. The result is:
63, 75, 27, 12 90
We reduce the effective size of the array to 4, making the highest index in the effective array now 3. The
largest element in this effective array (index 0-3) is at index 1, so we swap elements at index 1 and 3 (in
bold):
63, 12, 27, 75, 90
The next two steps give us:
27, 12, 63, 75, 90
12, 27, 63, 75, 90
The last effective array has only one element and needs no sorting. The entire array is now sorted.

Bubble Sort:
An alternate way of putting the largest element at the highest index in the array uses an algorithm called
bubble sort. While this method is neither as efficient, nor as straightforward, as selection sort, it is
popularly used to illustrate sorting. We include it here as an alternate method.
Like selection sort, the idea of bubble sort is to repeatedly move the largest element to the highest index
position of the array. As in selection sort, each iteration reduces the effective size of the array. The two
algorithms differ in how this is done. Rather than search the entire effective array to find the largest
element, bubble sort focuses on successive adjacent pairs of elements in the array, compares them, and
either swaps them or not. In either case, after such a step, the larger of the two elements will be in the
higher index position. The focus then moves to the next higher position, and the process is repeated.
When the focus reaches the end of the effective array, the largest element will have ``bubbled'' from
whatever its original position to the highest index position in the effective array.
Unsorted array:
45 67 12 34 25 39
Effective array of size 6:
45 12 34 25 39 67
Effective array of size 5:
12 34 25 39 45
Effective array of size 4:
12 25 34 39
Effective array of size 3:
12 25 34
Effective array of size 2:
12 25
Effective array of size 1:
12

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Sorted array:
12 25 34 39 45 67

Insertion Sort:
The two sorting algorithms we have looked at so far are useful when all of the data is already present in
an array, and we wish to rearrange it into sorted order. However, if we are reading the data into an array
one element at a time, we can take another approach - insert each element into its sorted position in the
array as we read it. In this way, we can keep the array in sorted form at all times. This algorithm is called
insertion sort.
Type numbers to be sorted, EOF to quit
Inserting Element: 23

Sorted Array:23
Inserting Element:12

SORTED ARRAY: 12 23
Inserting Element:35

SORTED ARRAY: 12 23 35
Inserting Element:30

SORTED ARRAY: 12 23 30 35
Inserting Element:47

SORTED ARRAY: 12 23 30 35 47
Inserting Element:10

SORTED ARRAY: 10 12 23 30 35 47
Insertion sort can be adapted to sorting an existing array. Each step works with a sub-array whose
effective size increases from two to the size of the array. The element at the highest index in the sub-
array is inserted into the current sub-array; the effective size is increased, etc.

Algorithm:

BUBBLESORT (A)
1. for i 1 to length[A]
2. do for j length[A] downto i + 1
3. do if A[j] < A[j - 1]
4. then exchange A[j] A[j - 1]

INSERTION-SORT (A)
1. for j 2 to length[A]
2. do key A[j]
3. //Insert A[j] into the sorted sequence A[1 .. j - 1].
4. ij-1
5. while i > 0 and A[i] > key
6. do A[i + 1] A[i]
7. ii1
8. A[i + 1] key

SELECTION-SORT (A)
1. for j 1 to length[A]
2. do key A[j]
3. loc j
4. for i j to length[A]
5. do if A[i ] < key

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
6. then key=A[i]
7. loc=i
8. if loc !=j
9. then Swap A[j] & A[i]

MERGE-SORT(A, p, r)
1. if p < r
2. then
3. MERGE-SORT(A, p, q)
4. MERGE-SORT(A, q + 1, r)
5. MERGE(A, p, q, r)

MERGE(A, p, q, r)
1. n1 q - p + 1
2. n2 r - q
3. //create arrays L[1 _ n1 + 1] and R[1 _ n2 + 1]
4. for i 1 to n1
5. do L[i] A[p + i - 1]
6. for j 1 to n2
7. do R[j] A[q + j]
8. L[n1 + 1]
9. R[n2 + 1]
10. i 1
11. j 1
12. for k p to r
13. do if L[i] R[j]
14. then A[k] L[i]
15. ii+1
16. else A[k] R[j]
17. jj+1

QUICKSORT(A, p, r)
1. if p < r
2. then q PARTITION(A, p, r)
3. QUICKSORT(A, p, q 1)
4. QUICKSORT(A, q + 1, r)

PARTITION(A, p, r)
1. x A[r]
2. i p 1
3. for j p to r 1
4. do if A[ j ] x
5. then i i + 1
6. exchange A[i ] A[ j ]
7. exchange A[i + 1] A[r]
8. return i + 1

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <time.h>
#include <malloc.h>
void insertion_sort(int *,int);
void selection_sort(int *,int);
void merge_sort(int *,int,int);
void quick_sort(int *,int,int);
void merge(int *,int,int,int);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
int partition(int *,int,int);
void bubble_sort(int *,int);
void print(int *,int);
void main()
{
int *a,*b,n,i;
struct timeval start, end;
double diff1,diff2;
FILE *fptr;
fptr=fopen("anujsort.txt","a");
fprintf(fptr," \n bubble_sort \t selection_sort \t insertion_sort \t merge_sort \t quick_sort ");
if(fptr==NULL)
{
printf("ERROE! File Not found");
exit(0);
}

for(n=100;n<=100000;n=n+100)
{
printf("\n Number of element is %d",n);
a=(int *)malloc(sizeof(int)*(n+2));
b=(int *)malloc(sizeof(int)*(n+2));
for(i=1;i<=n;i++)
a[i]=rand()%200;

gettimeofday(&start, NULL);
memcpy(&b[1],&a[1],n*sizeof(int));
bubble_sort(b,n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
fprintf(fptr," \n %d \t %lf ", n,diff1);

gettimeofday(&start, NULL);
memcpy(&b[1],&a[1],n*sizeof(int));
selection_sort(b,n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
fprintf(fptr,"\t %lf ",diff1);

gettimeofday(&start, NULL);
memcpy(&b[1],&a[1],n*sizeof(int));
insertion_sort(b,n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
fprintf(fptr,"\t %lf ",diff1);

gettimeofday(&start, NULL);
memcpy(&b[1],&a[1],sizeof(int)*n);
merge_sort(b,1,n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
fprintf(fptr,"\t %lf ",diff1);

gettimeofday(&start, NULL);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
memcpy(&b[1],&a[1],n*sizeof(int));
quick_sort(b,1,n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
fprintf(fptr,"\t %lf ",diff1);

}
fclose(fptr);
free(a);
free(b);
}
void print(int *b,int n)
{
int i;
for(i=1;i<=n;i++)
printf("%d \t",b[i]);
}
void bubble_sort(int *b,int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
for(j=1;j<n-i+1;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
}
void insertion_sort(int *b,int n)
{
int i,j,key;
for(i=2;i<=n;i++)
{
j=i-1;
key=b[i];
while(j>0 && b[j]>key)
{
b[j+1]=b[j];
j--;
}
b[j+1]=key;
}

}
void selection_sort(int *b,int n)
{
int i,j,loc,min,temp;
for(i=1;i<n;i++)
{
loc=i;

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
min=b[i];
for (j=i+1;j<=n;j++)
{
if(b[j]<min)
{
loc=j;
min=b[j];
}
}
if(i!=loc)
{
temp=b[i];
b[i]=b[loc];
b[loc]=temp;
}
}

}
void quick_sort(int *b,int p,int r)
{
if (p<r)
{
int q=partition(b,p,r);
quick_sort(b,p,q-1);
quick_sort(b,q+1,r);
}
}
int partition(int *b,int p,int r)
{
int x=b[r],i,j,temp;
i=p-1;
for(j=p;j<r;j++)
{
if(b[j]<=x)
{
i++;
temp=b[i];
b[i]=b[j];
b[j]=temp;
}

}
temp=b[i+1];
b[i+1]=b[r];
b[r]=temp;
return i+1;
}
void merge_sort(int *b,int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
merge_sort(b,p,q);
merge_sort(b,q+1,r);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
merge(b,p,q,r);
}
}
void merge(int *b,int p,int q,int r)
{
int n1,n2,i,j,k;
int l[60000],r1[60000],e;
n1=q-p+1;
n2=r-q;
//printf("\n p=%d q=%d r=%d",p,q,r);
//printf("\n n1=%d n2=%d",n1,n2);
memcpy(&l[1],&b[p],n1*sizeof(int));
memcpy(&r1[1],&b[q+1],n2*sizeof(int));
l[n1+1]=INT_MAX;
r1[n2+1]=INT_MAX;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(l[i]<r1[j])
{
b[k]=l[i];
i++;
}
else
{
b[k]=r1[j];
j++;
}
}
}
Output:
No of Time Analysis of sorting in Sec.
input Bubble sort Selection sort Insertion sort Merge sort Quick sort
100 0.000126 0.000071 0.000036 0.000053 0.000027
200 0.00042 0.000296 0.000122 0.000069 0.000058
300 0.000913 0.000534 0.000281 0.000108 0.000092
400 0.001594 0.000923 0.000462 0.000141 0.000123
500 0.00237 0.001326 0.001042 0.000165 0.000168
600 0.003096 0.001802 0.001022 0.0002 0.000179
700 0.003982 0.002463 0.001659 0.000173 0.000127
800 0.003801 0.001638 0.000976 0.000242 0.000227
900 0.004764 0.002102 0.001121 0.000162 0.000147
1000 0.00428 0.002593 0.001284 0.000166 0.000159
2000 0.016044 0.00962 0.005373 0.00035 0.000391
3000 0.038178 0.021366 0.011453 0.000537 0.00061
4000 0.069593 0.037803 0.019969 0.000724 0.000932
5000 0.113992 0.058946 0.031555 0.000917 0.001222
6000 0.169236 0.084855 0.045863 0.00111 0.00163
7000 0.238147 0.115334 0.06142 0.001311 0.002044
8000 0.318477 0.150445 0.081687 0.001486 0.002499
9000 0.402069 0.190412 0.102549 0.001725 0.003006
10000 0.526018 0.236734 0.130002 0.001899 0.003556
15000 1.192691 0.52792 0.28426 0.002874 0.006855

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
20000 2.164825 0.937573 0.505142 0.003879 0.01109
25000 3.405512 1.464137 0.790779 0.004879 0.016298
30000 4.952158 2.107938 1.131593 0.0059 0.022568
35000 6.771687 2.868809 1.544112 0.006992 0.029898
40000 8.877661 3.746013 2.01679 0.007999 0.038039
50000 13.958179 5.851672 3.147911 0.010005 0.057679
55000 17.028862 7.098946 3.897662 0.011145 0.068813
60000 20.232583 8.425842 4.578016 0.012111 0.080847
65000 23.796114 9.901025 5.345727 0.013053 0.094225
70000 27.499344 11.466667 6.149979 0.014401 0.108001
75000 31.523092 13.163347 7.086117 0.015491 0.124209
80000 35.959093 14.977144 8.10226 0.016409 0.140159
85000 40.608704 16.910255 9.145813 0.017307 0.156727
90000 46.102747 18.954277 10.229253 0.018522 0.175276
95000 50.960021 21.119049 11.365039 0.019449 0.193779
100000 56.332151 23.400077 12.607007 0.020544 0.214541

Analysis Chart of all above sorting:

Analysis chart of merge sort and quick sort:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion: We have successfully implemented the following sorting algorithm such as bubble sort,
insertion sort, selection sort, merge sort and quick sort. Form the implementation part it is concluded that
for the worst case scenario merge sort is better than among the sorting technique but it also required the
extra memory space in order of

Question & Answer:


Q 1.Complexity of bubble sort Selection Sort, Insertion Sort, Merge Sort and Quick Sort in best case, worst case
and Average case.
Ans: Complexity of bubble sort Selection Sort, Insertion Sort, Merge Sort and Quick Sort are shown in table 1:
Sorting Algorithm Best Case Average Case Worst Case
bubble sort
Selection Sort,
Insertion Sort, O(n)
Merge Sort
Quick Sort

Q 2. What is an algorithm?
Ans: An algorithm is a sequence of unambiguous instructions for solving a problem. i.e., for obtaining a
required output for any legitimate input in a finite amount of time

Q 3.How is an algorithms time efficiency measured?


Ans: Time efficiency indicates how fast the algorithm runs. An algorithms time efficiency is measured as a
function of its input size by counting the number of times its basic operation (running time) is executed. Basic
operation is the most time consuming operation in the algorithms innermost loop.
Q 4. What are the characteristics of an algorithm?
Every algorithm should have the following five characteristics
a. Input
b. Output
c. Definiteness
d. Effectiveness
e. Termination

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Therefore, an algorithm can be defined as a sequence of definite and effective instructions, which terminates
with the production of correct output from the given input. In other words, viewed little more formally, an
algorithm is a step by step formalization of a mapping function to map input set onto an output set.

Q 5.What do you mean by time complexity and space complexity of an algorithm?


Time complexity indicates how fast the algorithm runs. Space complexity deals with extra memory it require.
Time efficiency is analyzed by determining the number of repetitions of the basic operation as a function of
input size. Basic operation: the operation that contributes most towards the running time of the algorithm The
running time of an algorithm is the function defined by the number of steps (or amount of memory) required
to solve input instances of size n.

Q 6. Define Big Omega Notations


A function t(n) is said to be in (g(n)) , denoted t(n) ((g(n)) , if t(n) is bounded below by some positive
constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some nonnegative
integer n0 such that t(n) cg(n) for all for all n n0

Q 7.What are the different criteria used to improve the effectiveness of algorithm?
a. The effectiveness of algorithm is improved, when the design, satisfies the following constraints to
be minimum.
i. Time efficiency - how fast an algorithm in question runs.
ii. Space efficiency an extra space the algorithm requires
b. The algorithm has to provide result for all valid inputs.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 2
Aim: Write a C program to implementation and Time analysis of linear and binary search
algorithm.

Theory:
Linear Search:
Linear search is used on collections of items. It relies on the technique of traversing a list from start to
end by exploring properties of all the elements that are found on the way.
For example, consider an array of integers of size NN. You should find and print the position of all the
elements with value xx. Here, the linear search is based on the idea of matching each element from the
beginning of the list to the end of the list with the integer xx, and then printing the position of the element
if the condition is `True'.

Given an array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search, i.e
Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
If x matches with an element, return the index.
If x doesnt match with any of elements, return -1.

A simple approach is to do linear search. The time complexity of above algorithm is O(n). Another
approach to perform the same task is using Binary Search.

Binary Search:
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering
the whole array. If the value of the search key is less than the item in the middle of the interval, narrow
the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is
found or the interval is empty.

Algorithm:

Linear search (a, n, item)


1. for i 1 to n do
2. if(item==a[i])
3. return loc
4. if(i>n)
5. retun NULL

Binary Search (a, p, r, item)


1. if(p>r)
2. return NULL
3. else
4. q=(p+r)/2;
5. if(a[q]==item)
6. return q
7. else if (a[q]>item)
8. binary_search(a,p,q-1,item);
9. else
10. binary_search(a,q+1,r,item);

Source Code:
#include <stdio.h>
#include <limits.h>
#include <time.h>
#include <stdlib.h>
void linear_search(int *,int, int);
void binary_search(int *,int ,int,int);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
void insertion_sort(int *,int );
void main()
{
int *a,i,n,item;
struct timeval start,end;
double total;
FILE *fptr;
fptr=fopen("abc.txt","a+");
if(fptr==NULL)
{
printf("\n ERROR! File is not Found");
exit(1);
}
//printf("Enter the number of input");
//scanf("%d",&n);
fprintf(fptr,"number of input \t Time for Linear Search \t time for Binary Search");
for(n=1000;n<=100000;n=n+1000)
{
a=(int *)malloc(n*sizeof(int));
for(i=1;i<=n;i++)
a[i]=rand()%200;
//printf("Enter the Searching item");
//scanf("%d",&item);
item=rand()%200;
gettimeofday(&start,NULL);
linear_search(a,n,item);
gettimeofday(&end,NULL);
total=((end.tv_sec*1000000+end.tv_usec)-( start.tv_sec*1000000+start.tv_usec))/1000000.00;
//printf("Total Time for Linear Search =%lf",total);
fprintf(fptr,"\n %d \t %lf \t",n,total);
insertion_sort(a,n);
gettimeofday(&start,NULL)
binary_search(a,1,n,item);
gettimeofday(&end,NULL);
total=((end.tv_sec*1000000+end.tv_usec)+( start.tv_sec*1000000+start.tv_usec))/1000000.00;
//printf("Total Time for Linear Search =%lf",total);
fprintf(fptr,"\n %d \t %lf \t",n,total);
}
fclose(fptr);
}

void linear_search(int *a,int n,int item)


{
int i;
for (i=1;i<=n;i++)
if(item==a[i])
{
printf("\n Element is found at %d",i);
break;
}
if(i>n)
printf("\n Element is not found");
}

void binary_search(int *a,int p,int r,int item)


{
int q;
if(p>r)
printf("\n Element is not Found");
else

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
{
q=(p+r)/2;
if(a[q]==item)
printf("\n Element is found at %d",q);
else
{
if (a[q]>item)
binary_search(a,p,q-1,item);
else
binary_search(a,q+1,r,item);
}
}
}

void insertion_sort(int *a,int n)


{
int i,j,key;
for(i=2;i<=n;i++)
{
key=a[i];
j=i-1;
while(j>0 && a[j]>key)
{
a[j+1]=a[j];
j--;
}
a[j+1]=key;
}
}

Output:
No of Time Analysis in Sec.
Input Linear Search Binary Search
1000 0.000021 0.000012
2000 0.000029 0.000023
3000 0.000035 0.000026
4000 0.000039 0.000008
5000 0.000027 0.000025
6000 0.00004 0.000014
7000 0.000037 0.00001
8000 0.00004 0.000009
9000 0.000046 0.00001
10000 0.000051 0.00001
15000 0.000074 0.000009
20000 0.000097 0.000011
25000 0.000121 0.000011
30000 0.000144 0.000013
35000 0.000168 0.000019
40000 0.000191 0.000011
45000 0.000215 0.000014
50000 0.000239 0.00001
55000 0.000266 0.000011
60000 0.000288 0.000011
65000 0.000312 0.00001
70000 0.000334 0.000011
75000 0.000357 0.000012

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
80000 0.00038 0.000009
85000 0.000404 0.000012
90000 0.00043 0.000013
95000 0.000451 0.000013
100000 0.00048 0.000012

TIme Analysis of Birary Search & Linear Search


0.0006

0.0005

0.0004
Times in Sec

0.0003
Linear Search

0.0002 Binary Search

0.0001

0
1
6

71
76
11
16
21
26
31
36
41
46
51
56
61
66

81
86
91
96 No of Input *100

Conclusion: We have successfully implemented the linear search and binary search. Form the
implementation part it is concluded that Binary search is better than linear search.

Question & Answer:

Q 1. Define Binary Search


Binary Search is remarkably efficient algorithm for searching in a sorted array. It works by comparing a
search key K with the array's middle element A[m]. If they match, the algorithm stops; Otherwise, the same
operation is repeated recursively for the first half of the array if K< A[m] and for the second half if K > A[m]
A[0].............A[m-l] A[m] A[m+l]............. A[n-l]
Q 2. What can we say about the average case efficiency of binary search?
A sophisticated analysis shows that the average number of key comparisons made by binary search is only
slightly smaller than that in the worst case O
Q 3. How divide and conquer technique can be applied to binary trees?
Since the binary tree definition itself divides a binary tree into two smaller structures of the same type, the left
sub tree and the right sub tree, many problems about binary trees can be solved by applying the divide-
conquer technique.
Q 4. What do you mean by Searching problem?
The searching problem deals with finding a given value, called a search key, in a given set
Q 5. How many types of searching are there?
There are basically two types of searching:-linear search and Binary search.
Q 6. Define: linear search?
In linear search, we access each elements of an array one by one sequentially and see whether it is desired
element or not.
Q 7. Why binary search method is more efficient then liner search?
It is because less time is taken by linear search to search an element from the sorted list of elements.
Q 8. Efficiency of linear search?
The time taken or the number of comparisons made in searching a record in a search table determines the
efficiency of the technique.
Q 9. What do you understand by the term linear search is unsuccessful?

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Search will be unsuccessful if all the elements are accessed and the desired elements are not found.
Q 10. What is worse case?
In the worse case, the no. of average case we may have to scan half of the size of the array (n/2).
Q 11. What is the drawback of linear search?
There is no requisite for the linear Search.
Q 12. During linear search, when the record is present in first position then how many comparisons are
made?
Only one comparison.
Q 13. During linear search, when the record is present in last position then how many comparisons are
made?
N comparisons have to be made.
Q 14. What do you understand by binary search?
A binary search algorithm or binary chop is a technique for finding a particular value in a sorted list.
Q 15. Explain the steps of algorithm of binary search?
Step 1: Find the middle element of array f+1/2 = middle value
Step 2: Our derived element is greater than the main element
Q 16. Define the complexity of binary search?
In worst cause there is log (n+1) in the average causes.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 3
Aim: Implementation of max-heap sort algorithm
Theory:
Heaps: The (binary) heap data structure is an array object that can be viewed as a nearly complete
binary tree.

Each node of the tree corresponds to an element of the array that stores the value in the node. The tree is
completely filled on all levels except possibly the lowest, which is filled from the left up to a point. An
array A that represents a heap is an object with two attributes:
length[A], which is the number of elements in the array,
heap-size[A], the number of elements in the heap stored within array A.
That is, although A[1 . . length[A]] may contain valid numbers, no element past A[heap-size[A]], where
heap-size[A] length[A], is an element of the heap.

The root of the tree is A[1], and given the index i of a node, the indices of its parent PARENT(i ), left child
LEFT(i ), and right child RIGHT(i ) can be computed.
There are two kinds of binary heaps:
1) max-heaps
2) min-heaps

In both kinds, the values in the nodes satisfy a heap property, the specifics of which depend on the kind
of heap.
In a max-heap, the max-heap property is that for every node I other than the root,

that is, the value of a node is at most the value of its parent. Thus, the largest element in a max-heap is
stored at the root, and the subtree rooted at a node contains values no larger than that contained at the
node itself.
A min-heap is organized in the opposite way; the min-heap property is that for every node i other than
the root,

The smallest element in a min-heap is at the root. For the heap sort algorithm, we use max-heaps. Min-
heaps are commonly used in priority queues.
Viewing a heap as a tree, we define the height of a node in a heap to be the number of edges on the
longest simple downward path from the node to a leaf, and we define the height of the heap to be the
height of its root. Since a heap of n elements is based on a complete binary tree, its height is .
We shall see that the basic operations on heaps run in time at most proportional to the height of the tree
and thus take O(lgn) time. Following procedure are used in a sorting algorithm and a priority-queue data
structure.
The MAX-HEAPIFY procedure, which runs in O(lg n) time, is the key to maintaining the max-heap
property.
The BUILD-MAX-HEAP procedure, which runs in linear time, produces a maxheap from an unordered
input array.
The HEAPSORT procedure, which runs in O(n lg n) time, sorts an array in place.

The heapsort algorithm starts by using BUILD-MAX-HEAP to build a max-heap on the input array A[1 . .
n], where n = length[A]. Since the maximum element of the array is stored at the root A[1], it can be put
into its correct final position by exchanging it with A[n]. If we now discard node n from the heap (by
decrementing heap-size[A]), we observe that can easily be made into a max-heap. The

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
children of the root remain max-heaps, but the new root element may violate the max-heap property. All
that is needed to restore the max-heap property, however, is one call to MAX-HEAPIFY(A, 1), which leaves
a max-heap in . The heapsort algorithm then repeats this process for the maxheap of size
down to a heap of size 2.

Algorithm:
HEAPSORT(A)
1. BUILD-MAX-HEAP(A)
2. for i length[A] downto 2
3. do exchange A[1] A[i ]
4. heap-size[A] heap-size[A] 1
5. MAX-HEAPIFY(A, 1)

BUILD-MAX-HEAP(A)
1. heap-size[A] length[A]
2. for i length[A]/2 downto 1
3. do MAX-HEAPIFY(A, i )

MAX-HEAPIFY(A, i )
1. l LEFT(i )
2. r RIGHT(i )
3. if l heap-size[A] and A[l] > A[i ]
4. then largest l
5. else largest i
6. if r heap-size[A] and A[r] > A[largest]
7. then largest r
8. if largest != i
9. then exchange A[i ] A[largest]
10. MAX-HEAPIFY(A, largest)

PARENT(i )
1. return

LEFT(i )
1. return 2i

RIGHT(i )
1. return 2i + 1

Source Code:
// Heap Sort problem
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <malloc.h>
void heap_sort(int [],int );
void maxheapify(int [],int ,int);
void build_heap(int [],int);
void main()
{
int *a,i,n;
struct timeval start, end;
double diff;
FILE *fptr;
fptr=fopen("heapsort.txt","a");
for(n=10000;n<=1000000;n+=10000)
{ printf("Enter the number:");
printf("%d",n);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
fprintf(fptr,"%d \t",n);
a=(int*)malloc((n+1)*sizeof(int));
for(i=1;i<=n;i++)
a[i]=rand();
gettimeofday(&start, NULL);
heap_sort(a,n);
gettimeofday(&end, NULL);
diff = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 +
start.tv_usec))/1000000.0;
printf(" heapsort took: \t %lf \t sec.\n", diff);
fprintf(fptr,"%lf\n", diff);
/*
printf("\n print the sorted element\n");
for(i=1;i<=n;i++)
printf("%d \t",a[i]);
*/
free(a);
}
fclose(fptr);

}
void heap_sort(int a[],int n)
{
int i,temp,j;
build_heap(a,n);
for (i=n;i>1;i--)
{
temp=a[i];
a[i]=a[1];
a[1]=temp;
maxheapify(a,1,i-1);
}
}
void build_heap(int a[],int n)
{
int i;
for (i=n/2;i>=1;i--)
{
maxheapify(a,i,n);
}
}
void maxheapify(int a[],int i,int n)
{
int r=i*2+1;
int l=i*2;
int largest,temp;
if(l<=n && a[l]>a[i])
largest=l;
else largest=i;
if (r<=n && a[r]>a[largest])
largest=r;
if(largest!=i)
{
temp=a[i];
a[i]=a[largest];
a[largest]=temp;
maxheapify(a,largest,n);
}
}

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Output:

Conclusion:
Question & Answer:
Q 1. Define min-heap
A min-heap is a complete binary tree in which every element is less than or equal to its children.
All the principal properties of heaps remain valid for min-heaps, with some obvious modifications

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 4
Aim: Implementation and Time analysis of factorial program using iterative and recursive method
Theory:
There are two different methods to perform the repeat task are given follow:
Recursive approach: In recursive approach the function calls itself until the condition is met.
And it is slower than iteration, which means it uses more memory than iteration. Recursion is
like a selection structure, and which makes code smaller and clean. And a function partially
defined by itself. Here tracing the code will be more difficult in the case large programs.
Iterative approach: Iterative approach is a repetition process until the condition fails, here loops
are used such as for, while etc. Here code may be longer but it is faster than recursive. And it
consumes less memory compared to recursive approach. If the loop condition is always true in
such cases it will be an infinite loop.
Factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or
equal to n. Logic of calculating Factorial is very easy .
5! = 5 * 4 * 3 * 2 * 1 = 120.
It can be calculated easily using any programming Language. But if we implement with C & C++
programming language. The maximum size of data type is long long int. It cannot store more than
factorial of 20. So we have modify the method to calculate the factorial.

Algorithm:
Iterative_factorial(n):
1. Create an array res[ ] of MAX size where MAX is number of maximum digits in output.
2. Initialize value stored in res[ ] as 1 and initialize res_size (size of res[ ]) as 1.
3. Do following for all numbers from x = 2 to n......
i. Multiply x with res[ ] and update res[ ] and res_size to store the multiplication
result.

multiply (res, x)
1. Initialize carry as 0.
2. Do following for i = 0 to res_size 1 .....
i. Find value of res[i] * x + carry. Let this value be prod.
ii. Update res[i] by storing last digit of prod in it.
iii. Update carry by storing remaining digits in carry.
3. Put all digits of carry in res[ ] and increase res_size by number of digits in carry

Source Code:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
short int *a;
int digit=1;
void fact_loop(int );
void muyltiply(int );
void fact_recursive(int);
int main()
{
int n, i;
struct timeval start, end;
double diff1,diff2;
FILE *fptr;
fptr=fopen("Factorial1.txt","a");
//printf("Enter the number");
//scanf("%d",&n);
a=(short int *)malloc(200000*sizeof(short int));
for(n=100;n<10100;n+=100)

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
{
printf("Enter the number %d",n);
//a=(int *)malloc(1000*sizeof(int));
gettimeofday(&start, NULL);
a[0]=1;
digit=1;
fact_loop(n);
gettimeofday(&end, NULL);
diff1 = ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;
printf(" fact_loop took: \t %lf \t sec.\n", diff1);
//fprintf(fptr,"%lf\t", diff);

//for(i=digit-1;i>=0;i--)
// printf("%d",a[i]);
printf("digit=%d\n",digit);
//free(a);

//a=(int *)malloc(1000*sizeof(int));
gettimeofday(&end, NULL);
a[0]=1;
digit=1;

fact_recursive(n);
gettimeofday(&end, NULL);

diff2= ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec))/1000000.0;


printf(" fact_recursive took: \t %lf \t sec.\n", diff2);
fprintf(fptr,"%d \t %lf\t %lf \n",n,diff1,diff2);

/*printf("Recursive Factorial: \n");


for(i=digit-1;i>=0;i--)
printf("%d",a[i]);
printf("\n");
*/
//fclose(fptr);
//free(a);
}
fclose(fptr);
free(a);
return 0;
}

void fact_loop(int n)
{
int i;
a[0]=1;
for(i=1; i<=n; i++)
muyltiply(i);
}

void muyltiply(int i)
{
int x,carry,j;
carry=0;
for(j=0; j<digit; j++)
{
x = a[j]*i+carry;
a[j]=x%10;
carry = x/10;
}

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
while(carry>0)
{
a[digit] = carry%10;
carry= carry/10;
digit++;
}

}
void fact_recursive(int i)
{
if(i==1)
return;
else
{
muyltiply(i);
fact_recursive(i-1);
}
}

Output:
no of Time Analysis in Sec
input Iterative Method Recursive Method
100 0.000094 0.000231
200 0.000437 0.001123
300 0.0013 0.002912
400 0.002493 0.005537
500 0.003788 0.007885
600 0.004987 0.011307
700 0.006959 0.015234
800 0.009265 0.020654
900 0.012009 0.026574
1000 0.015283 0.033726
1500 0.080484 1.17172153
2000 0.151271 1.17803407
2500 0.242961 1.16977897
3000 0.351643 1.15369869
3500 0.497035 1.16877274
4000 0.655093 1.13663731
4500 0.837552 1.15109924
5000 1.044891 1.1426058
5500 1.298584 1.13895294
6000 1.565919 1.14520325
6500 1.894668 1.06962816
7000 2.166788 1.14359431
7500 2.500996 1.12669366
8000 2.890322 1.1472818
8500 3.317531 1.1504023
9000 3.79668 1.13910119
10000 4.651711 1.1353963

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion:
To calculate the factorial of a number there are two methods which are described above. After
the computation of C program, the result shows that Iterative method is almost 2 times faster
than recursive method.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 5
Aim: write a C program to implementation of a knapsack problem using dynamic programming.

Theory: Let i be the highest-numbered item in an optimal solution S for W pounds. Then S` = S - {i} is
an optimal solution for W - wi pounds and the value to the solution S is Vi plus the value of the
subproblem.
We can express this fact in the following formula: define c[i, w] to be the solution for items 1,2, . . . , i
and maximum weight w. Then

0 if i = 0 or w = 0
c[i,w] =
{ c[i-1, w]
max [vi + c[i-1, w-wi], c[i-1, w]}
if wi 0
if i>0 and w wi

This says that the value of the solution to i items either include ith item, in which case it is vi plus a
subproblem solution for (i - 1) items and the weight excluding wi, or does not include ith item, in which
case it is a subproblem's solution for (i - 1) items and the same weight. That is, if the thief picks item i,
thief takes vi value, and thief can choose from items w - wi, and get c[i - 1, w - wi] additional value. On
other hand, if thief decides not to take item i, thief can choose from item 1,2, . . . , i- 1 upto the weight
limit w, and get c[i - 1, w] value. The better of these two choices should be made.
The algorithm takes as input the maximum weight W, the number of items n, and the two sequences v =
<v1, v2, . . . , vn> and w = <w1, w2, . . . , wn>. It stores the c[i, j] values in the table, that is, a two
dimensional array, c[0 . . n, 0 . . w] whose entries are computed in a row-major order. That is, the first
row of c is filled in from left to right, then the second row, and so on. At the end of the computation, c[n,
w] contains the maximum value that can be picked into the knapsack.

Algorithm:
Source Code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<malloc.h>
void knapsack(int *,int *,int ,int );
void select_item(int **,int *,int ,int );
void main()
{
int i,n,*w,*p,m;
printf("Enter the numebr of item");
scanf("%d",&n);
w=(int *)malloc(sizeof(int)*n);
p=(int *)malloc(sizeof(int)*n);
printf("Enter the weight of item ");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);

printf("Enter the profit of item ");


for(i=1;i<=n;i++)
scanf("%d",&p[i]);

printf("Enter the capacity of the Knapsak");


scanf("%d",&m);

knapsack(w,p,n,m);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
}

void knapsack(int *w,int *p,int n,int m)


{
int **c;
int i,j;
c=(int **)malloc(sizeof(int*)*(n+1));
for(i=0;i<=n;i++)
c[i]=(int *)malloc(sizeof(int)*(m+1));
for(i=0;i<=n;i++)
c[i][0]=0;
for(j=1;j<=m;j++)
c[0][j]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
if (w[i]<=j)
{
if(p[i]+c[i-1][j-w[i]]>c[i-1][j])
c[i][j]=p[i]+c[i-1][j-w[i]];
else
c[i][j]=c[i-1][j];
}
else
c[i][j]=c[i-1][j];
}
/*printf("\n cost matrix\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
printf("%d \t",c[i][j]);
printf("\n");
}*/
printf("\n Maximum profit from 0/1 Knasack=%d",c[n][m]);
printf("selected Items are");
select_item(c,w,n,m);
}

void select_item(int **c,int *w,int i,int j)


{
//printf("\n i=%d j=%d\n",i,j);
//printf("\n ci=%d cj=%d\n",c[i][j],c[i-1][j]);
if(i==0 || j==0)
return ;
else {
if(c[i][j]!=c[i-1][j])
{
select_item(c,w,i-1,j-w[i]);
printf("%d \t",i);
}
else
{
select_item(c,w,i-1,j);
}
}
}

Output:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion:

Question & Answer:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 6
Aim: Implementation of chain matrix multiplication using dynamic programming.

Algorithm:
MATRIX-CHAIN-ORDER(p)
1. n length[p] 1
2. for i 1 to n
3. do m[i, i ] 0
4. for l 2 to n // l is the chain length.
5. do for i 1 to n l + 1
6. do j i + l 1
7. m[i, j ]
8. for k i to j 1
9. do q m[i, k] + m[k + 1, j ] + pi1 pk pj
10. if q < m[i, j ]
11. then m[i, j ] q
12. s[i, j ] k
13. return m and s

PRINT-OPTIMAL-PARENS(s, i, j )
1. if i = j
2. then print Ai
3. else print (
4. PRINT-OPTIMAL-PARENS(s, i, s[i, j ])
5. PRINT-OPTIMAL-PARENS(s, s[i, j ] + 1, j )
6. print )

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <malloc.h>
void matrix_chain(int *,int );
void print_pattern(int **,int ,int );
void main()
{
unsigned int *p,n,i;
printf("Enter the no of matrix:");
scanf("%d",&n);
p=(int*)malloc((n+1)*sizeof(int));
printf("\n Random Value of Matrix size");
for(i=0;i<=n;i++)
p[i]=rand()%40;
for(i=0;i<=n;i++)
printf("%d\t",p[i]);
matrix_chain(p,n);
}
void matrix_chain(int *p,int n)
{
long **c,q;
int i,j,l,k,**s;
c=(long **)malloc(n*sizeof(long *));
s=(int **)malloc(n*sizeof(int *));
for(i=1;i<=n;i++)
{
c[i]=(long *)malloc(n*sizeof(long));
s[i]=(int *)malloc(n*sizeof(int));
}

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
for(i=1;i<=n;i++)
c[i][i]=0;
for(l=2;l<=n;l++)
{
printf("%d \t",l);
for(i=1;i<=n-l+1;i++)
{
j=i+l-1;
c[i][j]=INT_MAX;
for(k=i;k<j;k++)
{
q=c[i][k]+c[k+1][j]+p[i-1]*p[k]*p[j];

if(q<c[i][j])
{
c[i][j]=q;
s[i][j]=k;
}
}
}
}
printf("\n cost Matrix for matrix chain");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%ld\t",c[i][j]);
printf("\n");
}
printf("\n Order of matrix chain Multiplication");
print_pattern(s,1,n);
printf("\n");

}
void print_pattern(int **s,int i,int j)
{
if (i==j)
{
printf("A%d",i);
}
else
{
printf("{");
print_pattern(s,i,s[i][j]);
print_pattern(s,s[i][j]+1,j);
printf("}");
}
}
Output:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 7
Aim: Implementation of making a change problem using dynamic programming
Theory
For example suppose, we live where there are coins for 1,4 and 6 units. if we have to make
change for 8 units, the greedy algorithm will propose doing so using one 6-unit coin and two 1-
unit coins, for a total of three coins. However it is clearly possible to do better that this we can
give the customer his change using just two 4-unit coins. Although the greedy algorithm does
not find this solution, it is easily obtained using dynamic programming.
Suppose the currency we are using has available coins of different denominations. Lets a coin of
denomination i, have value units. We suppose as is usual taht each . For
the time being we shall also supose taht we ahve an unlimited supply of coins of each
denomination. Finally suppose we have to give the customer coins of each being we shall also
suppose we have that we have to give the customer coins worth units, using as few coins as
possible.
To solve this problem by dynamic programming, we setup a table with onw
raw for each availabe denomination and one column for amount form 0 units to N units. in this
table will be the minimum number of coins required to pay an amount of j units,
, using only coins of denominations 1 to i, . the solution of the instance is
therfore given by if all we want to kanow is how many coins are needed. to filll in the
table, note first that is zero for every value of i. after this initialization, the table can be
filled either row form left to right, or column by column from top to bottom. to pay an amount j
using coins of denominations 1 to i, we have in general two choices. First we may choose not to
use any coins of denomination i, even though this is now permitted, in which case
. Alternatively, we may choose to use at least one coins of denomination, there
remains to be paid an amount of j-di units. to pay this take coins, so c
. sicne we want to minimize of coins used, we choose which ever alternative
is better. in general therfore

when i=1 one of the element to be compared falls outside the table. the same is true when
, it is convenient to think of such elements as having the value of . if i=1 and
, then both elemets to be comapred falls outside the table. In this case we
set to to indicate that it is impossible to pay an amount j using only coins to type 1.
Algorithm:
MAKING _CHANGE(N,d,n)
1. for i 1 to n
2. do c[i,0] 0
3. for i 1 to n
4. do for j 1 to N
5. if i=1 and j<d[i]
6. then c[i,j]
7. else if i==1
8. then c[i,j] 1+c[1,j-d[1]]
9. else if j<d[i]
10. then c[i,j] c[i-1,j]
11. else if c[i-1,j]< 1+c[i,j-d[i]]
12. c[i,j] c[i-1,j]
13. else then c[i,j] 1+c[i,j-d[i]]
14. return c[n,N]

Source Code:
// Coin change problem

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <malloc.h>
int n,m;
int coin_change(int *,int ,int);
void print_pattern(int **, int ,int ,int *);
void main()
{
int *d,i,ch;
int coin;
printf("Enter the number of type of coin:");
scanf("%d",&n);
d=(int*)malloc((n+1)*sizeof(int));
for(i=1;i<=n;i++)
scanf("%d",&d[i]);
printf("\n Enter the Change Value");
scanf("%d",&ch);
coin=coin_change(d,n,ch);
printf("No of Selected Coins are %d \n",coin);
}
int coin_change(int *d,int n,int m)
{
int **c,i,j;
c=(int **)malloc((n+1)*sizeof(int *));
for(i=0;i<=m;i++)
c[i]=(int *)malloc((m+1)*sizeof(int *));
for(i=1;i<=n;i++)
c[i][0]=0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(i==1 && j<d[i])
c[i][j]=INT_MAX;
else if (i==1)
c[1][j]=c[1][j-d[1]]+1;
else if(j< d[i])
c[i][j]=c[i-1][j];
else if (c[i-1][j]<c[i][j-d[i]]+1)
c[i][j]=c[i-1][j];
else
c[i][j]=c[i][j-d[i]]+1;
for(i=1;i<=n;i++)
{
for(j=0;j<=m;j++)
printf("%d \t ",c[i][j]);
printf("\n");
}
printf("Selected Coins:");
print_pattern(c,n,m,d);
return c[n][m];
}

void print_pattern(int **c,int i,int j,int d[])


{
if (j<=0)
return ;
else if (i==1 && j>=d[1])
{
print_pattern(c,1,j-d[1],d);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
printf("%d \n",d[1]);
}
else if(c[i][j]!=c[i-1][j] && j>=d[i])
{
print_pattern(c,i,j-d[i],d);
printf("%d \n",d[i]);
}
else
print_pattern(c,i-1,j,d);
}
Output:

Conclusion: Now we can find minimum number of coin required to make the change of
particular amount. Complexity of making change is .

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 8
Aim: Implementation of a knapsack problem using greedy algorithm
Theory:
We are given n objects and a knapsack. for i=1,2,.,n object I has a positive weight wi and the positive value vi.
the knapsack can carry a weight not exceeding W. our aim is to fill the knapsack in a way that maximizes the value
of included objects, while respecting the capacity constraint. in this problem we assumed that the objects can be
broken into smaller pieces, so we mau decide to carry onlty a fraction xi of object i, where 0<=xi<=1. In this case
object I contribute xiwi to the total weight in the knapsack and xivi to the value of the load. the problem can be
stated as follows:

Algorithm:
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <time.h>
void swap(int *,int *);
void swap_float(float *,float *);
void main()
{
int *w,*p,n,i,m,loc,u,j;
float *x,profit=0.0,*r,min;
printf("\n Enter the no of item");
scanf("%d",&n);
w=(int *)malloc(n*sizeof(int));
p=(int *)malloc(n*sizeof(int));
x=(float *)malloc(n*sizeof(float));
r=(float *)malloc(n*sizeof(float));
printf("enter the weight of the item");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("enter the profit of the item");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("Enter the Capacity of Knapsack");
scanf("%d",&m);
// find the ratio of p[i]/w[i];
for(i=1;i<=n;i++)
r[i]=(float)p[i]/w[i];
//sort the data according to ratio.
for(i=1;i<n;i++)
{
loc=i;
min=r[i];
for(j=i+1;j<=n;j++)
if(min<r[j])
{
loc=j;
min=r[j];

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
}
if(i!=loc)
{
swap_float(&r[i],&r[loc]);
swap(&p[i],&p[loc]);
swap(&w[i],&w[loc]);
}
}

u=m;
for(i=1;i<=n;i++)
x[i]=0.0;
for(i=1;i<=n;i++)
if(w[i]>u)
break;
else
{
x[i]=1.0;
u=u-w[i];
}
if(i<=n)
x[i]=(float)u/w[i];
for(i=1;i<=n;i++)
printf("%f \t",x[i]);
for(i=1;i<=n;i++)
profit=profit+x[i]*p[i];
printf("\n Profit of Knapsack=%f",profit );
}

void swap(int *x,int *y)


{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void swap_float(float *x,float *y)
{
float temp;
temp=*x;
*x=*y;
*y=temp;
}

Output:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion:
We Have successfully implement the knapsack Problem
Question & Answer:
Q 1. What are the constraints of knapsack problem?
To maximize:

The constraint is :

Where m is the bag capacity, n is the number of objects and for each object i and are the
weight and profit of object respectively.
Q 2. Write any two characteristics of Greedy Algorithm?
1) To solve a problem in an optimal way construct the solution from given set of candidates.
2) As the algorithm proceeds, two other sets get accumulated among this one set contains the
candidates that have been already considered and chosen while the other set contains the
candidates that have been considered but rejected.

Q 3. What is the Greedy approach?


The method suggests constructing solution through sequence of steps,each expanding partially
constructed solution obtained so far,until a complete solution is reached. On each step,the choice
must be
Feasible(satisfy problem constraints)
Locally optimal(best local choice among all feasible choices available on that step)
Irrevocable(once made,it cant be changed)
Q 4. What are the steps required to develop a greedy algorithm?
Determine the optimal substructure of the problem.
Develop a recursive solution.
Prove that at any stage of recursion one of the optimal choices is greedy choice.
Thus it is always safe to make greedy choice.
Show that all but one of the sub problems induced by having made the greedy choice are
empty.
Develop a recursive algorithm and convert into iterative algorithm.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 9
Aim: Implementation of Graph and Searching (DFS and BFS).
Theory:
Breadth-first search
Breadth-first search is one of the simplest algorithms for searching a graph and the archetype for many
important graph algorithms. Prims minimum-spanningtree algorithm (Section 23.2) and Dijkstras
single-source shortest-paths algorithm (Section 24.3) use ideas similar to those in breadth-first search.
Given a graph G = (V, E) and a distinguished source vertex s, breadth-first search systematically explores
the edges of G to discover every vertex that is reachable from s. It computes the distance (smallest
number of edges) from s to each reachable vertex. It also produces a breadth-first tree with root s that
contains all reachable vertices. For any vertex v reachable from s, the path in the breadth-first tree from s
to v corresponds to a shortest path from s to v in G, that is, a path containing the smallest number of
edges. The algorithm works on both directed and undirected graphs.
Breadth-first search is so named because it expands the frontier between discovered and undiscovered
vertices uniformly across the breadth of the frontier. That is, the algorithm discovers all vertices at
distance k from s before discovering any vertices at distance k + 1.
To keep track of progress, breadth-first search colors each vertex white, gray, or black. All vertices start
out white and may later become gray and then black. A vertex is discovered the first time it is
encountered during the search, at which time it becomes nonwhite. Gray and black vertices, therefore,
have been discovered, but breadth-first search distinguishes between them to ensure that the search
proceeds in a breadth-first manner. If (u, v) E and vertex u is black, then vertex v is either gray or
black; that is, all vertices adjacent to black vertices have been discovered.
Gray vertices may have some adjacent white vertices; they represent the frontier between discovered and
undiscovered vertices.
Breadth-first search constructs a breadth-first tree, initially containing only its root, which is the source
vertex s. Whenever a white vertex v is discovered in the course of scanning the adjacency list of an
already discovered vertex u, the vertex v and the edge (u, v) are added to the tree. We say that u is the
predecessor or parent of v in the breadth-first tree. Since a vertex is discovered at most once, it has at
most one parent. Ancestor and descendant relationships in the breadth-first tree are defined relative to the
root s as usual: if u is on a path in the tree from the root s to vertex v, then u is an ancestor of v and v is a
descendant of u.
The breadth-first-search procedure BFS below assumes that the input graph G = (V, E) is represented
using adjacency lists. It maintains several additional data structures with each vertex in the graph. The
color of each vertex u V is stored in the variable color[u], and the predecessor of u is stored in the
variable [u].
If u has no predecessor (for example, if u = s or u has not been discovered), then [u] = NIL. The distance
from the source s to vertex u computed by the algorithm is stored in d[u].

22.3 Depth-first search


The strategy followed by depth-first search is, as its name implies, to search deeper in the graph
whenever possible. In depth-first search, edges are explored out of the most recently discovered vertex v
that still has unexplored edges leaving it. When all of vs edges have been explored, the search
backtracks to explore edges leaving the vertex from which v was discovered. This process continues
until
we have discovered all the vertices that are reachable from the original source vertex. If any
undiscovered vertices remain, then one of them is selected as a new source and the search is repeated
from that source. This entire process is repeated until all vertices are discovered.
As in breadth-first search, whenever a vertex v is discovered during a scan of the adjacency list of an
already discovered vertex u, depth-first search records this event by setting vs predecessor field [v] to u.
Unlike breadth-first search, whose predecessor subgraph forms a tree, the predecessor subgraph produced
by a depth-first search may be composed of several trees, because the search may be repeated from
multiple sources.2 The predecessor subgraph of a depth-first search is therefore defined slightly
differently from that of a breadth-first search: we let G = (V, E ),
where

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
E = {([v], v) : v V and [v] _= NIL} .
The predecessor subgraph of a depth-first search forms a depth-first forest composed of several depth-
first trees. The edges in E are called tree edges.
As in breadth-first search, vertices are colored during the search to indicate their state. Each vertex is
initially white, is grayed when it is discovered in the search, and is blackened when it is finished, that is,
when its adjacency list has been examined completely. This technique guarantees that each vertex ends
up in exactly one depth-first tree, so that these trees are disjoint.
Besides creating a depth-first forest, depth-first search also timestamps each vertex. Each vertex v has
two timestamps: the first timestamp d[v] records when v is first discovered (and grayed), and the second
timestamp f [v] records when the search finishes examining vs adjacency list (and blackens v). These
timestamps are used in many graph algorithms and are generally helpful in reasoning about the behavior
of depth-first search.
The procedure DFS below records when it discovers vertex u in the variable d[u] and when it finishes
vertex u in the variable f [u]. These timestamps are integers between 1 and 2 |V|, since there is one
discovery event and one finishing event for each of the |V| vertices. For every vertex u,
d[u] < f [u] . (22.2)
Vertex u is WHITE before time d[u], GRAY between time d[u] and time f [u], and BLACK thereafter.
The following pseudocode is the basic depth-first-search algorithm. The input graph G may be undirected
or directed. The variable time is a global variable that we use for timestamping.

Algorithm:
BFS(G, s)
1. for each vertex
2. do color[u] WHITE
3. d[u]
4. [u] NIL
5. color[s] GRAY
6. d[s] 0
7. [s] NIL
8.
9. ENQUEUE(Q, s)
10. while
11. do u DEQUEUE(Q)
12. for each
13. do if color[v] = WHITE
14. then color[v] GRAY
15. d[v] d[u] + 1
16. [v] u
17. ENQUEUE(Q, v)
18. color[u] BLACK

DFS(G)
1. for each vertex
2. do color[u] WHITE
3. [u] NIL
4. time 0
5. for each vertex
6. do if color[u] = WHITE
7. then DFS-VISIT(u)

DFS-VISIT(u)
1. color[u] GRAY // White vertex u has just been discovered.
2. time time+1
3. d[u] time
4. for each //Explore edge (u, v).
5. do if color[v] = WHITE
6. then [v] u

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
7. DFS-VISIT(v)
8. color[u] BLACK // Blacken u; it is finished.
9. f [u] time time+1

Source Code:
include <stdio.h>
#include <stdlib.h>
#define Max 20
#define FALSE 0
#define TRUE 1
int adj[Max][Max];
int n;
int visited[Max];

void create_graph();
void display();
void bfs(int v);
void dfs(int v);
void dfs_rec(int v);
int main()
{
int i,v, choice;
create_graph();
while(1)
{
printf("1. Adjacency Matrix\n");
printf("2. DFS using stack\n");
printf("3. DFS using Recurssion\n");
printf("4. Return\n");
printf("Enter the choice");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n Print the Adjacency Matrix\n");
display();
break;
case 2: printf("\n Enter starting node for depth first search");
scanf("%d",&v);
for(i=1;i<=n;i++)
visited[i]=FALSE;
dfs(v);
break;
case 3: printf("\n Enter starting node for depth first search");
scanf("%d",&v);
for(i=1;i<=n;i++)
visited[i]=FALSE;
dfs_rec(v);
break;
case 5: printf("\n Enter starting node for breath first search");
scanf("%d",&v);
for(i=1;i<=n;i++)

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
visited[i]=FALSE;
bfs(v);
break;
case 4: return ;
default :printf("\n ERROR! Wrong Chice");
break;
}
}
return 0;
}
void create_graph()
{

int i,max_edge,origin,destination;
printf("Enter number of Vertices");
scanf("%d",&n);
max_edge=n*(n-1)/2;
for(i=1;i<=max_edge;i++)
{
printf("Enter Edge %d(0 0 to quit)",i);
scanf("%d %d",&origin,&destination);
if(origin==0 && destination==0)
break;

if(origin>n || destination>n|| origin<=0||destination<=0)


{
printf("Invalid edge \n");
i--;
}
else
{
adj[origin][destination]=1;
}
}
printf("Hello graph Created");
}

void display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d",adj[i][j]);
}
printf("\n");
}

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
}
void dfs_rec(int v)
{
int i;
visited[v]=TRUE;
printf("%d",v);
for(i=1;i<=n;i++)
if((adj[v][i]==1) && (visited[i]==FALSE))
dfs_rec(i);
}
void dfs(int v)
{
int i,stack[Max],top=0,pop,j,t;
top++;
stack[top]=v;
while(top>0)
{
pop=stack[top];
top--;
if(visited[pop]==FALSE)
{
printf("%d",pop);
visited[pop]=TRUE;
}
else
continue;
for(i=n;i>=1;i--)
{
if((adj[pop][i]==1)&& (visited[i]==FALSE))
{
top++;
stack[top]=i;
}
}
}
}

void bfs(int v)
{
int i,front,rear;
int que[20];
front=rear=-1;
printf("%d",v);
visited[v]=TRUE;
rear++;
front++;
que[rear]=v;
while(front<=rear)
{
v=que[front];

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
front++;
for(i=1;i<=n;i++)
{
if((adj[v][i]==1)&&visited[i]==FALSE)
{
printf("%d",i);
visited[i]=TRUE;
rear++;
que[rear]=i;

}
}
}
}
Output:
Conclusion: We have successfully implemented the BFS and DFS

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 10
Aim: Implement prims algorithm
Theory: Prims algorithm is a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain
two sets of vertices. The first set contains the vertices already included in the MST, the other set contains the
vertices not yet included. At every step, it considers all the edges that connect the two sets, and picks the minimum
weight edge from these edges. After picking the edge, it moves the other endpoint of the edge to the set containing
MST.
A group of edges that connects two set of vertices in a graph is called cut in graph theory. So, at every step of
Prims algorithm, we find a cut (of two sets, one contains the vertices already included in MST and other contains
rest of the vertices), pick the minimum weight edge from the cut and include this vertex to MST Set (the set that
contains already included vertices).
How does Prims Algorithm Work? The idea behind Prims algorithm is simple, a spanning tree means all vertices
must be connected. So the two disjoint subsets of vertices must be connected to make a Spanning Tree. And they
must be connected with the minimum weight edge to make it a Minimum Spanning Tree.
The idea of using key values is to pick the minimum weight edge from cut. The key values are used only for
vertices which are not yet included in MST, the key value for these vertices indicate the minimum weight edges
connecting them to the set of vertices included in MST.
Let us understand with the following example:

The set mstSet is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where
INF indicates infinite. Now pick the vertex with minimum key value. The vertex 0 is picked, include it in mstSet.
So mstSet becomes {0}. After including to mstSet, update key values of adjacent vertices. Adjacent vertices of 0
are 1 and 7. The key values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key
values, only the vertices with finite key values are shown. The vertices included in MST are shown in green color.

Pick the vertex with minimum key value and not already included in MST (not in mstSET). The vertex 1 is picked
and added to mstSet. So mstSet now becomes {0, 1}. Update the key values of adjacent vertices of 1. The key value
of vertex 2 becomes 8.

Pick the vertex with minimum key value and not already included in MST (not in mstSET). We can either pick
vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}. Update the key values of adjacent
vertices of 7. The key value of vertex 6 and 8 becomes finite (7 and 1 respectively).

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Pick the vertex with minimum key value and not already included in MST (not in mstSET). Vertex 6 is picked. So
mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent vertices of 6. The key value of vertex 5 and 8
are updated.

We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the following graph.

Algorithm:
MST-PRIM(G,w, r)
1. for each
2. do key[u]
3. [u] NIL
4. key[r] 0
5. Q V[G]
6. while
7. 7 do u EXTRACT-MIN(Q)
8. 8 for each
9. 9 do i and w(u, v) < key[v]
10. 10 then [v] u
11. 11 key[v] w(u, v)
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define Max 20
#define TEMP 0
#define PERM 1
#define FALSE 0
#define TRUE 1
#define infinity 99999
struct node1
{

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
int predecessor;
int dist;
int status;
};

struct edge1
{
int u;
int v;
}tree[Max];

int adj[Max][Max];
int n;

void create_graph();
void display();
int maketree(struct edge1 tree[Max],int *weight);
int all_perm(struct node1 state[Max]);

void main()
{
int i,j;
int wt_tree=0,count;
int path[Max];
//struct egde1 Tree[20];

create_graph();
printf("Adjacency Matrix");
display();
printf("Edge to be included in spanning tree are \n");
count=maketree(tree,&wt_tree);
for(i=1;i<=count;i++)
{
printf("%d->",tree[i].u);
printf("%d\n",tree[i].v);
}
printf("weight of the minimum spanning tree is %d\n",wt_tree);
}
void create_graph()
{

int i,max_edge,origin,destination,wt;
printf("Enter number of Vertices");
scanf("%d",&n);
max_edge=n*(n-1)/2;
for(i=1;i<=max_edge;i++)
{
printf("Enter Edge %d(0 0 to quit)",i);
scanf("%d %d",&origin,&destination);
if(origin==0 && destination==0)

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
break;
printf("Enetr the weight for this edge");
scanf("%d",&wt);
if(origin>n || destination>n|| origin<=0||destination<=0)
{
printf("Invalid edge \n");
i--;
}
else
{
adj[origin][destination]=wt;
adj[destination][origin]=wt;
}
}
if(i<n-1)
{
printf("Spanning tree is not possible");
exit(1);
}
}

void display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d",adj[i][j]);
}
printf("\n");
}

int maketree(struct edge1 tree[Max],int *weight)


{
struct node1 state[Max];
int i,k,min,count,current,newdist;
int m;
int u1,v1;
*weight=0;
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].dist=infinity;
state[i].status=TEMP;
}
state[1].predecessor=0;
state[1].dist=0;

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
state[1].status=TEMP;
current=1;
count=0;
while(all_perm(state)!=TRUE)
{
for(i=1;i<=n;i++)
{
if(adj[current][i]>0 && state[i].status==TEMP)
{
if(adj[current][i]<state[i].dist)
{
state[i].predecessor=current;
state[i].dist=adj[current][i];
}
}
}
min=infinity;
for(i=1;i<=n;i++)
{
if(state[i].status==TEMP && state[i].dist<min)
{
min=state[i].dist;
current=i;
}
}
}
state[current].status=PERM;
u1=state[current].predecessor;
v1=current;
count++;
tree[count].u=u1;
tree[count].v=v1;
*weight=*weight+adj[u1][v1];
}

int all_perm(struct node1 state[Max])


{
int i;
for(i=1;i<=n;i++)
if(state[i].status==TEMP)
return FALSE;
return TRUE;
}
Output:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion: We have successfully implemented the prims Algorithm

Question & Answer:


Q 1. What is Minimum Spanning Tree?
Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree
and connects all the vertices together. A single graph can have many different spanning
trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted,
connected and undirected graph is a spanning tree with weight less than or equal to the weight of
every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge
of the spanning tree.
Q 2. How many edges does a minimum spanning tree has?
A minimum spanning tree has (V 1) edges where V is the number of vertices in the given
graph.
Q 3. What are the applications of Minimum Spanning Tree?
max bottleneck paths
LDPC codes for error correction
image registration with Renyi entropy
learning salient features for real-time face verification
reducing data storage in sequencing amino acids in a protein
model locality of particle interactions in turbulent fluid flows
autoconfig protocol for Ethernet bridging to avoid cycles in a network
Q 4. Define Prim's Algorithm
Prim's algorithm is a greedy algorithm for constructing a minimum spanning tree of a weighted
connected graph.It works by attaching to a previously constructed subtree a vertex to the vertices
already in the tree.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 11
Aim: Implement kruskals algorithm
Theory:
Below are the steps for finding MST using Kruskals algorithm
a) Sort all the edges in non-decreasing order of their weight.
b) Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is
not formed, include this edge. Else, discard it.
c) Repeat step#2 until there are (V-1) edges in the spanning tree.
The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a
cycle in the MST constructed so far. Let us understand it with an example: Consider the below input graph.

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 1) = 8
edges.
After sorting:
Weight Src Dest Weight Src Dest

1 7 6 7 7 8

2 8 2 8 0 7

3 6 5 8 1 2

4 0 1 9 3 4

4 2 5 10 5 4

6 8 6 11 1 7

7 2 3 14 3 5

Now pick all edges one by one from sorted list of edges
1. Pick edge 7-6: No cycle is formed, include it.

2. Pick edge 8-2: No cycle is formed, include it.

3. Pick edge 6-5: No cycle is formed, include it.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
4. Pick edge 0-1: No cycle is formed, include it.

a.
5. Pick edge 2-5: No cycle is formed, include it

7. Pick edge 8-6: Since including this edge results in cycle, discard it.
8. Pick edge 2-3: No cycle is formed, include it.

9. Pick edge 7-8: Since including this edge results in cycle, discard it.
10. Pick edge 0-7: No cycle is formed, include it.

11. Pick edge 1-2: Since including this edge results in cycle, discard it.
12. Pick edge 3-4: No cycle is formed, include it.

Since the number of edges included equals (V 1), the algorithm stops here.

Algorithm:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
MST-KRUSKAL(G,w)
1. A
2. for each vertex v V[G]
3. do MAKE-SET(v)
4. sort the edges of E into nondecreasing order by weight w
5. for each edge (u, v) E, taken in nondecreasing order by weight
6. do if FIND-SET(u) != FIND-SET(v)
7. then A A {(u, v)}
8. UNION(u, v)
9. return A

Source Code:
#include<stdio.h>
#include<stdlib.h>
#define Max 20
void create_garph();
struct edge{
int u;
int v;
int w;
struct edge *link;
} *front1=NULL;
int father[Max];
struct edge tree[max];
int n;
int wt_tree=0;
int count=0;
void make_tree();
void insert_tree(int i,int j,int wt);
void insert_pque(int i,int j,int wt);
struct edge *del_pque();
kruskal()
{
int i;
create_graph();
make_tree();
printf("Edge to be included in spanning tree are \n");
for(i=1;i<=count;i++)
{
printf("%d->"tree[i].u);
printf("%d\n"tree[i].v);
}
printf("weight of the minimum spanning tree is %d\n",wt_tree);
}

void create_graph()
{
int i,wt,max_edge,origin,destination;
printf("Enter the number of node");
scanf("%d",&n);
max_edge=n*(n-1)/2;
for(i=1;i<=max_edge;i++)
{
printf("Enter edge %d (0 0 to quit)",i);
scanf("%d %d",&origin,&destination);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
if(origin==0&&destination==0)
break;
printf("enter the weight for this edge");
scanf("%d",&wt);
if(origin>n || destination>n|| origin<=0||destination<=0)
{
printf("Invalid edge \n");
i--;
}
else
insert_pque(origin,destination,wt);
}
if(i<n-1)
{
printf("Spanning tree is not possible");
exit(1);
}
}
void make_tree()
{
struct edge *tmp;
int node1,node2,root_n1,root_n2;
while(count<n-1)
{
tmp=del_pque()
node1=tmp->u;
node2=tmp->v;
printf("\n n1=%d,n2=%d",node1,node2);
while(node1>0)
{
root_n1=node1;
node1=father[node1];
}
while(node2>0)
{
root_n2=node2;
node2=father[node2];
}
if(root_n2!=root_n1)
{
insert_tree(tmp->u,tmp->v,tmp->weight);
wt_tree=wt_tree+tmp.w;
father[root_n2]=root_n1;
}
}
}
void insert_tree(int i,int j,int wt)
{
printf("this edge inserted in the spanning tree\n");
count++;
tree[count].u=i;
tree[count].v=j;
tree[count].w=wt;
}

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
void insert_pque(int i,int j,int wt)
{
struct edge *tmp,*q;
tmp=(struct edge *)malloc (sizeof(stuct edge));
tmp->u=i;
tmp->v=j;
tmp->w=wt;
if(fornt1==NULL || tmp->w<fornt1->w)
{
tmp->link=fornt1;
front1=tmp;
}
else
{
q=fornt1;
while (q->link!=NULL && q->link->w<=tmp->w)
q=q->link;
temp->link=q->link;
q->link=tmp;
if(q->link==NULL)
tmp->link=NULL;
}
}
struct edge *del_pque()
{
struct edge *tmp;
tmp=front1;
printf("Edge processed is %d->%d%d\n ",tmp->u,tmp->v,tmp->w);
front1=form1->link;
return tmp;

}
Output:

Conclusion: We have successfully implemented the kruskal Algorithm

Question & Answer:


Q 1. Define Spanning Tree
A Spanning Tree of a connected graph is its connected acyclic subgraph(i.e., a tree) that contains
all the vertices of the graph.
Q 2. Define Minimum Spanning Tree
A minimum spanning tree of a weighted connected graph is its spanning tree of the smallest
weight ,where the weight of a tree is defined as the sum of the weights on all its edges
Q 3. Define Kruskal's Algorithm

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Kruskal's algorithm looks at a minimum spanning tree for a weighted connected graph G =(V,E)
as an acyclic subgraph with | V| - 1 edges for which the sum of the edge weights is the smallest.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Experiment No: 12
Aim: Implement LCS problem.
Theory:
What if the pattern does not occur in the text? It still makes sense to find the longest subsequence that
occurs both in the pattern and in the text. This is the longest common subsequence problem. Since the
pattern and text have symmetric roles, from now on we won't give them different names but just call
them strings A and B. We'll use m to denote the length of A and n to denote the length of B.
Note that the automata-theoretic method above doesn't solve the problem -- instead it gives the longest
prefix of A that's a subsequence of B. But the longest common subsequence of A and B is not always a
prefix of A.
Why might we want to solve the longest common subsequence problem? There are several motivating
applications.
Molecular biology. DNA sequences (genes) can be represented as sequences of four letters
ACGT, corresponding to the four submolecules forming DNA. When biologists find a new
sequences, they typically want to know what other sequences it is most similar to. One way of
computing how similar two sequences are is to find the length of their longest common
subsequence.
File comparison. The Unix program "diff" is used to compare two different versions of the same
file, to determine what changes have been made to the file. It works by finding a longest
common subsequence of the lines of the two files; any line in the subsequence has not been
changed, so what it displays is the remaining set of lines that have changed. In this instance of
the problem we should think of each line of a file as being a single complicated character in a
string.
Screen redisplay. Many text editors like "emacs" display part of a file on the screen, updating the
screen image as the file is changed. For slow dial-in terminals, these programs want to send the
terminal as few characters as possible to cause it to update its display correctly. It is possible to
view the computation of the minimum length sequence of characters needed to update the
terminal as being a sort of common subsequence problem (the common subsequence tells you the
parts of the display that are already correct and don't need to be changed).
So we want to solve the longest common subsequence problem by dynamic programming. To do this, we
first need a recursive solution. The dynamic programming idea doesn't tell us how to find this, it just
gives us a way of making the solution more efficient once we have.
Let's start with some simple observations about the LCS problem. If we have two strings, say "nematode
knowledge" and "empty bottle", we can represent a subsequence as a way of writing the two so that
If we draw lines connecting the letters in the first string to the corresponding letters in the second, no two
lines cross (the top and bottom endpoints occur in the same order, the order of the letters in the
subsequence). Conversely any set of lines drawn like this, without crossings, represents a subsequence.
Algorithm:
LCS-LENGTH(X, Y )
1. m length[X]
2. n length[Y ]
3. for i 1 to m
4. do c[i, 0] 0
5. for j 0 to n
6. do c[0, j ] 0
7. for i 1 to m
8. do for j 1 to n
9. do if xi = yj
10. then c[i, j ] c[i 1, j 1] + 1
11. b[i, j ] &
12. else if c[i 1, j ] c[i, j 1]
13. then c[i, j ] c[i 1, j ]
14. b[i, j ]
15. else c[i, j ] c[i, j 1]

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
16. b[i, j ]
17. return c and b

PRINT-LCS(b, X, i, j )
1. if i = 0 or j = 0
2. then return
3. if b[i, j ] = &
4. then PRINT-LCS(b, X, i 1, j 1)
5. print xi
6. else if b[i, j ] =
7. then PRINT-LCS(b, X, i 1, j )
8. else PRINT-LCS(b, X, i, j 1)

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
void lcs(char *,char *,int ,int );
void print_lcs(int **,char *,int , int );
char *randstring(int length) {

static char charset[] = "GTAC";


char *randomString = NULL;
int n;
if (length) {
randomString = malloc(sizeof(char) * (length +2));

if (randomString) {
for (n=1;n<=length;n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}

randomString[length] = '\0';
}
}

return randomString;
}
void main()
{
char *x, *y;
int i,j,n,m;
printf("Enter the length of first string ");
scanf("%d",&n);
x=randstring(n);
printf("Enter the length of Second string ");
scanf("%d",&m);
y=randstring(m);
puts(x);
puts(y);
lcs(x,y,n,m);
}
void lcs(char *x,char *y,int n,int m)
{
int **c,**s;
int i,j;
c=(int **)malloc(sizeof(int *)*(n+1));
s=(int **)malloc(sizeof(int *)*(n+1));

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
for(i=0;i<=n;i++)
{
c[i]=(int *)malloc(sizeof(int)*(m+1));
s[i]=(int *)malloc(sizeof(int)*(m+1));
}
for(i=0;i<=n;i++)
c[i][0]=0;
for(j=1;j<=m;j++)
c[0][j]=0;
printf("hello");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
if(x[i]==y[j])
{
c[i][j]=c[i-1][j-1]+1;
s[i][j]=1;
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
s[i][j]=2;
}
else
{
c[i][j]=c[i][j-1]+1;
s[i][j]=3;
}
}
printf("Cost Matrix");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
printf("%d \t",c[i][j]);
printf("\n");
}
printf("\n Structure Matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
printf("%d \t",s[i][j]);
printf("\n");
}
printf("\n length of LCS=%d",c[n][m]);
printf("\n Comman String are : ");
print_lcs(s,x,n,m);
}
void print_lcs(int **s,char *x,int i, int j)
{
if (i==0 || j==0)
return;
if(s[i][j]==1)
{
print_lcs(s,x,i-1,j-1);
printf("%c",x[i]);
}
else if(s[i][j]==2)
print_lcs(s,x,i-1,j);
else
print_lcs(s,x,i,j-1);

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
}
Output:

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara
Conclusion:
We have successfully implemented the longest common subsequence.

Question & Answer:


Q 1. 1)Define Dynamic Programming
Dynamic programming is a technique for solving problems with overlapping problems. Typically, these
subproblems arise from a recurrence relating a solution to a given problem with solutions to its smaller
subproblems of the same type. Rather than solving overlapping subproblems again and again, dynamic
programming suggests solving each of the smaller sub problems only once and recording the results in a table
from which we can then obtain a solution to the original problem.

Subject Teacher: Anuj Kumar Jain, Assistant Professor, Dept. CSE, ITM Universe Vadodara

You might also like