SlideShare a Scribd company logo
Data Structures
Recursion
Andres Mendez-Vazquez
May 6, 2015
1 / 19
Images/cinvestav-
Outline
1 Introduction
2 Recursive Method
Questions to Answer When Designing a Recursion
3 Design guidelines for successful recursion
Examples of Code with Innite Recursion
Example
2 / 19
Images/cinvestav-
What is recursion?
Fact
Sometimes, the best way to solve a problem is by solving a smaller version
of the exact same problem rst
Example
You can build a house by hiring a contractor.
The contractor in turn hires several subcontractors to complete
portions of the house.
Each subcontractor might hire other subcontractors to help.
3 / 19
Images/cinvestav-
What is recursion?
Fact
Sometimes, the best way to solve a problem is by solving a smaller version
of the exact same problem rst
Example
You can build a house by hiring a contractor.
The contractor in turn hires several subcontractors to complete
portions of the house.
Each subcontractor might hire other subcontractors to help.
3 / 19
Images/cinvestav-
Another Example
Example: Principal Idea You do your part until your friend nishes
and tells you
4 / 19
Images/cinvestav-
Recursive Method
Denition
A method that calls itself is a recursive method.
The invocation is a recursive call or recursive invocation.
The previous example can be seen in code as follow
5 / 19
Images/cinvestav-
Recursive Method
Denition
A method that calls itself is a recursive method.
The invocation is a recursive call or recursive invocation.
The previous example can be seen in code as follow
/∗∗ Counts down from a given positive integer .
@param integer an integer  0 ∗/
p u b l i c s t a t i c v o i d countDown ( i n t i n t e g e r )
{
System . out . p r i n t l n ( i n t e g e r ) ;
i f ( i n t e g e r  1)
countDown ( i n t e g e r − 1 ) ;
} // end countDown
5 / 19
Images/cinvestav-
Example with 3
Tracing the recursive call countDown(3)
//Client
public static void main(...)
{
countDown(3);
...
}
public static void countDown(3)
{
System.out.println(3);
countDown(3 – 1);
}
if (3  1)
public static void countDown(2)
{
System.out.println(2);
countDown(2 – 1);
}
if (2  1)
public static void countDown(1)
{
System.out.println(1);
}
if (1  1)
6 / 19
Images/cinvestav-
Outline
1 Introduction
2 Recursive Method
Questions to Answer When Designing a Recursion
3 Design guidelines for successful recursion
Examples of Code with Innite Recursion
Example
7 / 19
Images/cinvestav-
Questions to answer when designing a recursive solution
First
What part of the solution can you contribute directly?
Second
What smaller but identical problem has a solution that, when taken with
your contribution, provides the solution to the original problem?
Third
When does the process end? That is, what smaller but identical problem
has a known solution, and have you reached this problem, or base case?
8 / 19
Images/cinvestav-
Questions to answer when designing a recursive solution
First
What part of the solution can you contribute directly?
Second
What smaller but identical problem has a solution that, when taken with
your contribution, provides the solution to the original problem?
Third
When does the process end? That is, what smaller but identical problem
has a known solution, and have you reached this problem, or base case?
8 / 19
Images/cinvestav-
Questions to answer when designing a recursive solution
First
What part of the solution can you contribute directly?
Second
What smaller but identical problem has a solution that, when taken with
your contribution, provides the solution to the original problem?
Third
When does the process end? That is, what smaller but identical problem
has a known solution, and have you reached this problem, or base case?
8 / 19
Images/cinvestav-
For countDown
Answer 1
The method countDown displays the given integer rst.
Answer 2
The smaller problem is counting down from integer - 1.
Answer 3
The if statement asks if the process has reached the base case. In our case
integer = 1.
9 / 19
Images/cinvestav-
For countDown
Answer 1
The method countDown displays the given integer rst.
Answer 2
The smaller problem is counting down from integer - 1.
Answer 3
The if statement asks if the process has reached the base case. In our case
integer = 1.
9 / 19
Images/cinvestav-
For countDown
Answer 1
The method countDown displays the given integer rst.
Answer 2
The smaller problem is counting down from integer - 1.
Answer 3
The if statement asks if the process has reached the base case. In our case
integer = 1.
9 / 19
Images/cinvestav-
Design guidelines for successful recursion
First
The method must be given an input value.
Second
The method denition must contain logic that involves this input value and
leads to dierent cases.
Third
One or more of these cases should provide a solution that does not require
recursion. These are the base cases, or stopping cases.
Fourth
One or more cases must include a recursive invocation of the method using
a smaller argument.
10 / 19
Images/cinvestav-
Design guidelines for successful recursion
First
The method must be given an input value.
Second
The method denition must contain logic that involves this input value and
leads to dierent cases.
Third
One or more of these cases should provide a solution that does not require
recursion. These are the base cases, or stopping cases.
Fourth
One or more cases must include a recursive invocation of the method using
a smaller argument.
10 / 19
Images/cinvestav-
Design guidelines for successful recursion
First
The method must be given an input value.
Second
The method denition must contain logic that involves this input value and
leads to dierent cases.
Third
One or more of these cases should provide a solution that does not require
recursion. These are the base cases, or stopping cases.
Fourth
One or more cases must include a recursive invocation of the method using
a smaller argument.
10 / 19
Images/cinvestav-
Design guidelines for successful recursion
First
The method must be given an input value.
Second
The method denition must contain logic that involves this input value and
leads to dierent cases.
Third
One or more of these cases should provide a solution that does not require
recursion. These are the base cases, or stopping cases.
Fourth
One or more cases must include a recursive invocation of the method using
a smaller argument.
10 / 19
Images/cinvestav-
So, be careful
Innite recursion
A recursive method that does not check for a base case, or that misses the
base case, will execute forever. This situation is known as innite
recursion.
Which is known as
This situation is known as innite recursion.
11 / 19
Images/cinvestav-
So, be careful
Innite recursion
A recursive method that does not check for a base case, or that misses the
base case, will execute forever. This situation is known as innite
recursion.
Which is known as
This situation is known as innite recursion.
11 / 19
Images/cinvestav-
Outline
1 Introduction
2 Recursive Method
Questions to Answer When Designing a Recursion
3 Design guidelines for successful recursion
Examples of Code with Innite Recursion
Example
12 / 19
Images/cinvestav-
Example of code with innite recursion
Code
/∗∗ Counts down from a given positive integer .
@param integer an integer  0 ∗/
p u b l i c s t a t i c v o i d countDown ( i n t i n t e g e r )
{
System . out . p r i n t l n ( i n t e g e r ) ;
countDown ( i n t e g e r − 1 ) ;
} // end countDown
13 / 19
Images/cinvestav-
Recursive Methods That Return a Value
The nice stu about recursion
You can return values
For example
We can compute the sum 1 + 2 + 3 + ... + n
14 / 19
Images/cinvestav-
Recursive Methods That Return a Value
The nice stu about recursion
You can return values
For example
We can compute the sum 1 + 2 + 3 + ... + n
14 / 19
Images/cinvestav-
How the code will look
Partial Code
/∗∗ @param n an integer  0
@return the sum 1 + 2 + . . . + n ∗/
p u b l i c s t a t i c i n t sumOf ( i n t n )
{
i n t sum ;
// What do we put here?
r e t u r n sum ;
} // end sumOf
15 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Debugging a recursive method
Something Notable
1 Does the method have at least one input value?
2 Does the method contain a statement that tests an input value and
leads to dierent cases?
3 Did you consider all possible cases? Does at least one of these cases
cause at least one recursive call?
4 Do these recursive calls involve smaller arguments, smaller tasks, or
tasks that get closer to the solution?
5 If these recursive calls produce or return correct results, will the
method produce or return a correct result?
6 Is at least one of the cases a base case that has no recursive call?
7 Are there enough base cases?
8 Does each base case produce a result that is correct for that case?
9 If the method returns a value, does each of the cases return a value?
16 / 19
Images/cinvestav-
Outline
1 Introduction
2 Recursive Method
Questions to Answer When Designing a Recursion
3 Design guidelines for successful recursion
Examples of Code with Innite Recursion
Example
17 / 19
Images/cinvestav-
Now, what if we solve a recursive function
What we want to solve
n choose k (combinations)
We have
n
k
=
n − 1
k
+
n − 1
k − 1
, with 1  k  n (1)
Base Case
n
1
= n (k = 1) ,
n
n
= 1(k = n) (2)
18 / 19
Images/cinvestav-
Now, what if we solve a recursive function
What we want to solve
n choose k (combinations)
We have
n
k
=
n − 1
k
+
n − 1
k − 1
, with 1  k  n (1)
Base Case
n
1
= n (k = 1) ,
n
n
= 1(k = n) (2)
18 / 19
Images/cinvestav-
Now, what if we solve a recursive function
What we want to solve
n choose k (combinations)
We have
n
k
=
n − 1
k
+
n − 1
k − 1
, with 1  k  n (1)
Base Case
n
1
= n (k = 1) ,
n
n
= 1(k = n) (2)
18 / 19
Images/cinvestav-
Base Code so you can start
Base Code
c l a s s C o m b i n a ti o n s {
p u b l i c s t a t i c i n t Co m b i n a t io n s ( i n t n , i n t k )
{
}
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
{
}
}
19 / 19

More Related Content

What's hot

Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
Srikanth
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm design
Nahid Hasan
 
Chapter 05 computer arithmetic
Chapter 05 computer arithmeticChapter 05 computer arithmetic
Chapter 05 computer arithmetic
IIUI
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
paramalways
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Simplilearn
 

What's hot (20)

Lecture 2 role of algorithms in computing
Lecture 2   role of algorithms in computingLecture 2   role of algorithms in computing
Lecture 2 role of algorithms in computing
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automation
 
Algorithm hierarchy
Algorithm hierarchyAlgorithm hierarchy
Algorithm hierarchy
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm design
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
 
Programming with matlab session 3 notes
Programming with matlab session 3 notesProgramming with matlab session 3 notes
Programming with matlab session 3 notes
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Algorithmic research
Algorithmic researchAlgorithmic research
Algorithmic research
 
Chapter 05 computer arithmetic
Chapter 05 computer arithmeticChapter 05 computer arithmetic
Chapter 05 computer arithmetic
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
 
Dynamic programming prasintation eaisy
Dynamic programming prasintation eaisyDynamic programming prasintation eaisy
Dynamic programming prasintation eaisy
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
The Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 MigrationThe Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 Migration
 
Algorithm Design Presentation
Algorithm Design PresentationAlgorithm Design Presentation
Algorithm Design Presentation
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Tbs910 linear programming
Tbs910 linear programmingTbs910 linear programming
Tbs910 linear programming
 
Chapter one
Chapter oneChapter one
Chapter one
 

Viewers also liked

Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
Tech_MX
 

Viewers also liked (19)

Problem 8
Problem 8Problem 8
Problem 8
 
ELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURESELEMENTARY DATASTRUCTURES
ELEMENTARY DATASTRUCTURES
 
Unit 4 jwfiles
Unit 4 jwfilesUnit 4 jwfiles
Unit 4 jwfiles
 
Data representation UNIT-1
Data representation UNIT-1Data representation UNIT-1
Data representation UNIT-1
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema Theorem07.2 Holland's Genetic Algorithms Schema Theorem
07.2 Holland's Genetic Algorithms Schema Theorem
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
 
Hashing
HashingHashing
Hashing
 
algorithm Unit 4
algorithm Unit 4 algorithm Unit 4
algorithm Unit 4
 
Modified Genetic Algorithm for Solving n-Queens Problem
Modified Genetic Algorithm for Solving n-Queens ProblemModified Genetic Algorithm for Solving n-Queens Problem
Modified Genetic Algorithm for Solving n-Queens Problem
 
Cs6402 design and analysis of algorithms impartant part b questions appasami
Cs6402 design and analysis of algorithms  impartant part b questions appasamiCs6402 design and analysis of algorithms  impartant part b questions appasami
Cs6402 design and analysis of algorithms impartant part b questions appasami
 
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questioCS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
DESIGN AND ANALYSIS OF ALGORITHM (DAA)
DESIGN AND ANALYSIS OF ALGORITHM (DAA)DESIGN AND ANALYSIS OF ALGORITHM (DAA)
DESIGN AND ANALYSIS OF ALGORITHM (DAA)
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 

Similar to Preparation Data Structures 02 recursion

Tips & tricks for Quantitative Aptitude
Tips & tricks for Quantitative AptitudeTips & tricks for Quantitative Aptitude
Tips & tricks for Quantitative Aptitude
Amber Bhaumik
 

Similar to Preparation Data Structures 02 recursion (20)

Divide and Conquer Case Study
Divide and Conquer Case StudyDivide and Conquer Case Study
Divide and Conquer Case Study
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 
Approximation algorithms
Approximation  algorithms Approximation  algorithms
Approximation algorithms
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
 
Knightstour
KnightstourKnightstour
Knightstour
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
 
Dynamic Programming: Smith-Waterman
Dynamic Programming: Smith-WatermanDynamic Programming: Smith-Waterman
Dynamic Programming: Smith-Waterman
 
N Queens problem
N Queens problemN Queens problem
N Queens problem
 
From jUnit to Mutationtesting
From jUnit to MutationtestingFrom jUnit to Mutationtesting
From jUnit to Mutationtesting
 
3. CPT121 - Introduction to Problem Solving - Module 1 - Unit 3.pptx
3. CPT121 - Introduction to Problem Solving - Module 1 - Unit 3.pptx3. CPT121 - Introduction to Problem Solving - Module 1 - Unit 3.pptx
3. CPT121 - Introduction to Problem Solving - Module 1 - Unit 3.pptx
 
Simplex Algorithm
Simplex AlgorithmSimplex Algorithm
Simplex Algorithm
 
MATHS
MATHSMATHS
MATHS
 
Tips & tricks for Quantitative Aptitude
Tips & tricks for Quantitative AptitudeTips & tricks for Quantitative Aptitude
Tips & tricks for Quantitative Aptitude
 
Unit i
Unit iUnit i
Unit i
 
DATA STRUCTURE.pdf
DATA STRUCTURE.pdfDATA STRUCTURE.pdf
DATA STRUCTURE.pdf
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
Why recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docxWhy recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docx
 

More from Andres Mendez-Vazquez

Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
Andres Mendez-Vazquez
 

More from Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
 
Zetta global
Zetta globalZetta global
Zetta global
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
 

Recently uploaded

Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
Avinash Rai
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 

Recently uploaded (20)

Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
Forest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDFForest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDF
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 

Preparation Data Structures 02 recursion

  • 2. Images/cinvestav- Outline 1 Introduction 2 Recursive Method Questions to Answer When Designing a Recursion 3 Design guidelines for successful recursion Examples of Code with Innite Recursion Example 2 / 19
  • 3. Images/cinvestav- What is recursion? Fact Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem rst Example You can build a house by hiring a contractor. The contractor in turn hires several subcontractors to complete portions of the house. Each subcontractor might hire other subcontractors to help. 3 / 19
  • 4. Images/cinvestav- What is recursion? Fact Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem rst Example You can build a house by hiring a contractor. The contractor in turn hires several subcontractors to complete portions of the house. Each subcontractor might hire other subcontractors to help. 3 / 19
  • 5. Images/cinvestav- Another Example Example: Principal Idea You do your part until your friend nishes and tells you 4 / 19
  • 6. Images/cinvestav- Recursive Method Denition A method that calls itself is a recursive method. The invocation is a recursive call or recursive invocation. The previous example can be seen in code as follow 5 / 19
  • 7. Images/cinvestav- Recursive Method Denition A method that calls itself is a recursive method. The invocation is a recursive call or recursive invocation. The previous example can be seen in code as follow /∗∗ Counts down from a given positive integer . @param integer an integer 0 ∗/ p u b l i c s t a t i c v o i d countDown ( i n t i n t e g e r ) { System . out . p r i n t l n ( i n t e g e r ) ; i f ( i n t e g e r 1) countDown ( i n t e g e r − 1 ) ; } // end countDown 5 / 19
  • 8. Images/cinvestav- Example with 3 Tracing the recursive call countDown(3) //Client public static void main(...) { countDown(3); ... } public static void countDown(3) { System.out.println(3); countDown(3 – 1); } if (3 1) public static void countDown(2) { System.out.println(2); countDown(2 – 1); } if (2 1) public static void countDown(1) { System.out.println(1); } if (1 1) 6 / 19
  • 9. Images/cinvestav- Outline 1 Introduction 2 Recursive Method Questions to Answer When Designing a Recursion 3 Design guidelines for successful recursion Examples of Code with Innite Recursion Example 7 / 19
  • 10. Images/cinvestav- Questions to answer when designing a recursive solution First What part of the solution can you contribute directly? Second What smaller but identical problem has a solution that, when taken with your contribution, provides the solution to the original problem? Third When does the process end? That is, what smaller but identical problem has a known solution, and have you reached this problem, or base case? 8 / 19
  • 11. Images/cinvestav- Questions to answer when designing a recursive solution First What part of the solution can you contribute directly? Second What smaller but identical problem has a solution that, when taken with your contribution, provides the solution to the original problem? Third When does the process end? That is, what smaller but identical problem has a known solution, and have you reached this problem, or base case? 8 / 19
  • 12. Images/cinvestav- Questions to answer when designing a recursive solution First What part of the solution can you contribute directly? Second What smaller but identical problem has a solution that, when taken with your contribution, provides the solution to the original problem? Third When does the process end? That is, what smaller but identical problem has a known solution, and have you reached this problem, or base case? 8 / 19
  • 13. Images/cinvestav- For countDown Answer 1 The method countDown displays the given integer rst. Answer 2 The smaller problem is counting down from integer - 1. Answer 3 The if statement asks if the process has reached the base case. In our case integer = 1. 9 / 19
  • 14. Images/cinvestav- For countDown Answer 1 The method countDown displays the given integer rst. Answer 2 The smaller problem is counting down from integer - 1. Answer 3 The if statement asks if the process has reached the base case. In our case integer = 1. 9 / 19
  • 15. Images/cinvestav- For countDown Answer 1 The method countDown displays the given integer rst. Answer 2 The smaller problem is counting down from integer - 1. Answer 3 The if statement asks if the process has reached the base case. In our case integer = 1. 9 / 19
  • 16. Images/cinvestav- Design guidelines for successful recursion First The method must be given an input value. Second The method denition must contain logic that involves this input value and leads to dierent cases. Third One or more of these cases should provide a solution that does not require recursion. These are the base cases, or stopping cases. Fourth One or more cases must include a recursive invocation of the method using a smaller argument. 10 / 19
  • 17. Images/cinvestav- Design guidelines for successful recursion First The method must be given an input value. Second The method denition must contain logic that involves this input value and leads to dierent cases. Third One or more of these cases should provide a solution that does not require recursion. These are the base cases, or stopping cases. Fourth One or more cases must include a recursive invocation of the method using a smaller argument. 10 / 19
  • 18. Images/cinvestav- Design guidelines for successful recursion First The method must be given an input value. Second The method denition must contain logic that involves this input value and leads to dierent cases. Third One or more of these cases should provide a solution that does not require recursion. These are the base cases, or stopping cases. Fourth One or more cases must include a recursive invocation of the method using a smaller argument. 10 / 19
  • 19. Images/cinvestav- Design guidelines for successful recursion First The method must be given an input value. Second The method denition must contain logic that involves this input value and leads to dierent cases. Third One or more of these cases should provide a solution that does not require recursion. These are the base cases, or stopping cases. Fourth One or more cases must include a recursive invocation of the method using a smaller argument. 10 / 19
  • 20. Images/cinvestav- So, be careful Innite recursion A recursive method that does not check for a base case, or that misses the base case, will execute forever. This situation is known as innite recursion. Which is known as This situation is known as innite recursion. 11 / 19
  • 21. Images/cinvestav- So, be careful Innite recursion A recursive method that does not check for a base case, or that misses the base case, will execute forever. This situation is known as innite recursion. Which is known as This situation is known as innite recursion. 11 / 19
  • 22. Images/cinvestav- Outline 1 Introduction 2 Recursive Method Questions to Answer When Designing a Recursion 3 Design guidelines for successful recursion Examples of Code with Innite Recursion Example 12 / 19
  • 23. Images/cinvestav- Example of code with innite recursion Code /∗∗ Counts down from a given positive integer . @param integer an integer 0 ∗/ p u b l i c s t a t i c v o i d countDown ( i n t i n t e g e r ) { System . out . p r i n t l n ( i n t e g e r ) ; countDown ( i n t e g e r − 1 ) ; } // end countDown 13 / 19
  • 24. Images/cinvestav- Recursive Methods That Return a Value The nice stu about recursion You can return values For example We can compute the sum 1 + 2 + 3 + ... + n 14 / 19
  • 25. Images/cinvestav- Recursive Methods That Return a Value The nice stu about recursion You can return values For example We can compute the sum 1 + 2 + 3 + ... + n 14 / 19
  • 26. Images/cinvestav- How the code will look Partial Code /∗∗ @param n an integer 0 @return the sum 1 + 2 + . . . + n ∗/ p u b l i c s t a t i c i n t sumOf ( i n t n ) { i n t sum ; // What do we put here? r e t u r n sum ; } // end sumOf 15 / 19
  • 27. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 28. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 29. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 30. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 31. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 32. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 33. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 34. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 35. Images/cinvestav- Debugging a recursive method Something Notable 1 Does the method have at least one input value? 2 Does the method contain a statement that tests an input value and leads to dierent cases? 3 Did you consider all possible cases? Does at least one of these cases cause at least one recursive call? 4 Do these recursive calls involve smaller arguments, smaller tasks, or tasks that get closer to the solution? 5 If these recursive calls produce or return correct results, will the method produce or return a correct result? 6 Is at least one of the cases a base case that has no recursive call? 7 Are there enough base cases? 8 Does each base case produce a result that is correct for that case? 9 If the method returns a value, does each of the cases return a value? 16 / 19
  • 36. Images/cinvestav- Outline 1 Introduction 2 Recursive Method Questions to Answer When Designing a Recursion 3 Design guidelines for successful recursion Examples of Code with Innite Recursion Example 17 / 19
  • 37. Images/cinvestav- Now, what if we solve a recursive function What we want to solve n choose k (combinations) We have n k = n − 1 k + n − 1 k − 1 , with 1 k n (1) Base Case n 1 = n (k = 1) , n n = 1(k = n) (2) 18 / 19
  • 38. Images/cinvestav- Now, what if we solve a recursive function What we want to solve n choose k (combinations) We have n k = n − 1 k + n − 1 k − 1 , with 1 k n (1) Base Case n 1 = n (k = 1) , n n = 1(k = n) (2) 18 / 19
  • 39. Images/cinvestav- Now, what if we solve a recursive function What we want to solve n choose k (combinations) We have n k = n − 1 k + n − 1 k − 1 , with 1 k n (1) Base Case n 1 = n (k = 1) , n n = 1(k = n) (2) 18 / 19
  • 40. Images/cinvestav- Base Code so you can start Base Code c l a s s C o m b i n a ti o n s { p u b l i c s t a t i c i n t Co m b i n a t io n s ( i n t n , i n t k ) { } p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { } } 19 / 19