SlideShare a Scribd company logo
1 of 31
Chapter 8
Recursion
Recursion
• Recursion is a programming technique in which a
method can call itself to fulfill its purpose
• A procedure that is defined in terms of itself
• In some situations, a recursive definition can be
an appropriate way to express a concept
• Before applying recursion to programming, it is
best to practice thinking recursively
8 - 2
Java Software Structures, 4th Edition, Lewis/Chase
Infinite Recursion
• All recursive definitions must have a non-
recursive part
• If they don't, there is no way to terminate the
recursive path
• A definition without a non-recursive part causes
infinite recursion
• This problem is similar to an infinite loop -- with
the definition itself causing the infinite “looping”
• The non-recursive part is called the base case
8 - 3
Java Software Structures, 4th Edition, Lewis/Chase
Example
• A simple recursive method that keeps calling
itself forever (no base case)
• A simple recursive method that keeps calling
itself until a base case (count from n to zero)
Java Software Structures, 4th Edition, Lewis/Chase 8 - 4
Recursion in Math
• Mathematical formulas are often expressed
recursively
• N!, for any positive integer N, is defined to be the
product of all integers between 1 and N inclusive
• This definition can be expressed recursively:
1! = 1
N! = N * (N-1)!
• A factorial is defined in terms of another factorial
until the base case of 1! is reached
8 - 5
Java Software Structures, 4th Edition, Lewis/Chase
A mathematical look
• We are familiar with
f(x) = 3x+5
• How about
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 6
Calculate f(5)
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
• f(5) = f(7)-3
• f(7) = f(9)-3
• f(9) = f(11)-3
• f(11) = 3(11)+5
= 38
But we have not determined what f(5) is yet!
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 7
Calculate f(5)
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
 f(5) = f(7)-3 = 29
 f(7) = f(9)-3 = 32
 f(9) = f(11)-3 = 35
 f(11) = 3(11)+5
= 38
Working backwards we see that f(5)=29
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 8
12/31/2022
Series of calls
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 9
f(5)
f(7)
f(9)
f(11)
12/31/2022
Calculate f(5)
package myjava;
import java.util.*;
public class MyJava {
public static int fun( int x )
{
if( x > 10 )
return (3*x+5); //base step
else
return fun( x +2 ) -3; //recursive step
}
public static void main (String args[]) {
System.out.print("the result of fun(5) = “ + fun( 5 ) );
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 10
12/31/2022
Recursive Programming
• A method in Java can invoke itself; if set up that
way, it is called a recursive method
• The code of a recursive method must handle
both the base case and the recursive case
• Each call sets up a new execution environment,
with new parameters and new local variables
• As always, when the method completes, control
returns to the method that invoked it (which may
be another instance of itself)
8 - 11
Java Software Structures, 4th Edition, Lewis/Chase
Recursive Programming
• Consider the problem of computing the sum of
all the integers between 1 and N, inclusive
• If N is 5, the sum is
1 + 2 + 3 + 4 + 5
• This problem can be expressed recursively as:
The sum of 1 to N is N plus the sum of 1 to N-1
8 - 12
Java Software Structures, 4th Edition, Lewis/Chase
Summation
1+2+3+4+5+…+100
Sum(100) = 1+2+3+…+100
= 1+2+…+ 99 + 100
= sum (99) + 100
sum(n) = sum (n-1) + n
sum(0) = 0
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 13
Recursive step
Base step
12/31/2022
Summation Method
package myjava;
import java.util.*;
public class MyJava {
public static int sum( int n )
{
if(n == 0) //base step
return (0);
else //recursive step
return(sum (n-1) +n);
}
public static void main (String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("enter any number :" );
int x = scan.nextInt();
System.out.println("the summation from 1 to " +x+ " = "+ sum( x ));
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 14
12/31/2022
Recursion vs. Iteration
• Just because we can use recursion to solve a
problem, doesn't mean we should
• For instance, we usually would not use recursion
to solve the sum of 1 to N
• The iterative version is easier to understand (in
fact there is a formula that computes it without a
loop at all)
• You must be able to determine when recursion is
the correct technique to use
8 - 15
Java Software Structures, 4th Edition, Lewis/Chase
Recursion vs. Iteration
• Every recursive solution has a corresponding
iterative solution
• A recursive solution may simply be less efficient
• Furthermore, recursion has the overhead of
multiple method invocations
• However, for some problems recursive solutions
are often more simple and elegant to express
8 - 16
Java Software Structures, 4th Edition, Lewis/Chase
Factorial
4! = 4 * 3 * 2 * 1
n! = n * (n-1) * … * 1
4! = 4 * 3!
n! = n * (n-1)!
factorial(n) = n * factorial(n-1) //recursive step
factorial(1) = 1 //base step
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 17
12/31/2022
Method Factorial
package myjava;
import java.util.*;
public class MyJava {
public static int facto( int n )
{
if(n == 1) //base step
return (1);
else //recursive step
return(facto (n-1)*n);
}
public static void main (String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("enter any number :" );
int x = scan.nextInt();
System.out.println("the summation from 1 to " +x+ " = "+ facto( x ));
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 18
12/31/2022
Fibonacci Sequence Numbers
0, 1, 1, 2, 3, 5, 8, 13, …
Fib(n) = Fib(n-1) + Fib(n-2) // recursive step
Fib(0) = 0 //base step
Fib(1) = 1 //base step
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 19
12/31/2022
Recursive Implementation of Fibonacci
Numbers
package myjava;
import java.util.*;
public class MyJava {
public static int Fib(int n){
if(n<=1)
return n;
else
return (Fib(n-1)+Fib(n-2));
}
public static void main (String args[]) {
int x =5;
System.out.println("the Fib of " +x + " equal to "+ Fib( x ) );
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 20
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2)
Fib(2) Fib(1)
Fib(1) Fib(0)
Fib(1) Fib(0)
Fib(1)
Fib(2)
Fib(1) Fib(0)
5
1
0
1 1
2 1
1
0
1
0
1
1
3 2
12/31/2022
End of Summer 2130
Java Software Structures, 4th Edition, Lewis/Chase 8 - 21
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Tower Of Hanoi
• Goal: Move all disks from A to C
• Rule:
– No bigger disk is on top of smaller disk at any
time
– Move one disk at a time
A B C
4 disks
12/31/2022
22
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Tower Of Hanoi
• 1 disk moves from A to C: Simple!
• 2 disks move from A to C
A B C
2 disks
1 2 3
12/31/2022
23
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
N disks from A to C?
1. Move n-1 disks from A to B
2. Move disk n from A to C
3. Move n-1 disks from B to C
A B C
disk n
1
n-1 disks
2
3
12/31/2022
24
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
25
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
26
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
27
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Recursive Code For Hanoi Tower (Trace of Recursive)
package myjava;
import java.util.*;
public class MyJava {
public static void move(int n, char start, char finish, char buf){
if(n==1) // stop condition: move one disk
System.out.println("Move from " +start + " to "+ finish );
else{
move(n-1,start,buf,finish); // move n-1 from start to buf using
//finish as temporary storage
System.out.println("Move from " +start + " to "+ finish );
move(n-1,buf,finish,start); // move n-1 from buf to finish using
//start as temporary storage
}};
public static void main (String args[]) {
move(3, 'A', 'C', 'B');
}
}
12/31/2022
28
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Demo Of Hanoi
• A nice animation of Hanoi online:
– https://www.mathsisfun.com/games/
12/31/2022
29
Analyzing Recursive Algorithms
• To determine the order of a loop, we determined the
order of the body of the loop multiplied by the number
of loop executions
• Similarly, to determine the order of a recursive method,
we determine the the order of the body of the method
multiplied by the number of times the recursive method
is called
• In our recursive solution to compute the sum of integers
from 1 to N, the method is invoked N times and the
method itself is O(1)
• So the order of the overall solution is O(n)
8 - 30
Java Software Structures, 4th Edition, Lewis/Chase
Analyzing Recursive Algorithms
• For the Towers of Hanoi puzzle, the step of
moving one disk is O(1)
• But each call results in calling itself twice more,
so for N > 1, the growth function is
f(n) = 2n – 1
• This is exponential efficiency: O(2n)
• As the number of disks increases, the number of
required moves increases exponentially
8 - 31
Java Software Structures, 4th Edition, Lewis/Chase

More Related Content

Similar to 8. Recursion.pptx

81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programsAbhishek Jena
 
Scaling Deep Learning with MXNet
Scaling Deep Learning with MXNetScaling Deep Learning with MXNet
Scaling Deep Learning with MXNetAI Frontiers
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingzukun
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語Kiyotaka Oku
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9ecomputernotes
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaRavikiran J
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia岳華 杜
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
20170415 當julia遇上資料科學
20170415 當julia遇上資料科學20170415 當julia遇上資料科學
20170415 當julia遇上資料科學岳華 杜
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學岳華 杜
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Project
 
Scientific visualization with_gr
Scientific visualization with_grScientific visualization with_gr
Scientific visualization with_grJosef Heinen
 

Similar to 8. Recursion.pptx (20)

81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
 
Scaling Deep Learning with MXNet
Scaling Deep Learning with MXNetScaling Deep Learning with MXNet
Scaling Deep Learning with MXNet
 
slides.07.pptx
slides.07.pptxslides.07.pptx
slides.07.pptx
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
Survey onhpcs languages
Survey onhpcs languagesSurvey onhpcs languages
Survey onhpcs languages
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
20170415 當julia遇上資料科學
20170415 當julia遇上資料科學20170415 當julia遇上資料科學
20170415 當julia遇上資料科學
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes Presentation
 
Scientific visualization with_gr
Scientific visualization with_grScientific visualization with_gr
Scientific visualization with_gr
 

Recently uploaded

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

8. Recursion.pptx

  • 2. Recursion • Recursion is a programming technique in which a method can call itself to fulfill its purpose • A procedure that is defined in terms of itself • In some situations, a recursive definition can be an appropriate way to express a concept • Before applying recursion to programming, it is best to practice thinking recursively 8 - 2 Java Software Structures, 4th Edition, Lewis/Chase
  • 3. Infinite Recursion • All recursive definitions must have a non- recursive part • If they don't, there is no way to terminate the recursive path • A definition without a non-recursive part causes infinite recursion • This problem is similar to an infinite loop -- with the definition itself causing the infinite “looping” • The non-recursive part is called the base case 8 - 3 Java Software Structures, 4th Edition, Lewis/Chase
  • 4. Example • A simple recursive method that keeps calling itself forever (no base case) • A simple recursive method that keeps calling itself until a base case (count from n to zero) Java Software Structures, 4th Edition, Lewis/Chase 8 - 4
  • 5. Recursion in Math • Mathematical formulas are often expressed recursively • N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive • This definition can be expressed recursively: 1! = 1 N! = N * (N-1)! • A factorial is defined in terms of another factorial until the base case of 1! is reached 8 - 5 Java Software Structures, 4th Edition, Lewis/Chase
  • 6. A mathematical look • We are familiar with f(x) = 3x+5 • How about f(x) = 3x+5 if x > 10 f(x) = f(x+2) -3 otherwise PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 6
  • 7. Calculate f(5) f(x) = 3x+5 if x > 10 f(x) = f(x+2) -3 otherwise • f(5) = f(7)-3 • f(7) = f(9)-3 • f(9) = f(11)-3 • f(11) = 3(11)+5 = 38 But we have not determined what f(5) is yet! PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 7
  • 8. Calculate f(5) f(x) = 3x+5 if x > 10 f(x) = f(x+2) -3 otherwise  f(5) = f(7)-3 = 29  f(7) = f(9)-3 = 32  f(9) = f(11)-3 = 35  f(11) = 3(11)+5 = 38 Working backwards we see that f(5)=29 PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 8 12/31/2022
  • 9. Series of calls PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 9 f(5) f(7) f(9) f(11) 12/31/2022
  • 10. Calculate f(5) package myjava; import java.util.*; public class MyJava { public static int fun( int x ) { if( x > 10 ) return (3*x+5); //base step else return fun( x +2 ) -3; //recursive step } public static void main (String args[]) { System.out.print("the result of fun(5) = “ + fun( 5 ) ); } } PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 10 12/31/2022
  • 11. Recursive Programming • A method in Java can invoke itself; if set up that way, it is called a recursive method • The code of a recursive method must handle both the base case and the recursive case • Each call sets up a new execution environment, with new parameters and new local variables • As always, when the method completes, control returns to the method that invoked it (which may be another instance of itself) 8 - 11 Java Software Structures, 4th Edition, Lewis/Chase
  • 12. Recursive Programming • Consider the problem of computing the sum of all the integers between 1 and N, inclusive • If N is 5, the sum is 1 + 2 + 3 + 4 + 5 • This problem can be expressed recursively as: The sum of 1 to N is N plus the sum of 1 to N-1 8 - 12 Java Software Structures, 4th Edition, Lewis/Chase
  • 13. Summation 1+2+3+4+5+…+100 Sum(100) = 1+2+3+…+100 = 1+2+…+ 99 + 100 = sum (99) + 100 sum(n) = sum (n-1) + n sum(0) = 0 PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 13 Recursive step Base step 12/31/2022
  • 14. Summation Method package myjava; import java.util.*; public class MyJava { public static int sum( int n ) { if(n == 0) //base step return (0); else //recursive step return(sum (n-1) +n); } public static void main (String args[]) { Scanner scan=new Scanner(System.in); System.out.println("enter any number :" ); int x = scan.nextInt(); System.out.println("the summation from 1 to " +x+ " = "+ sum( x )); } } PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 14 12/31/2022
  • 15. Recursion vs. Iteration • Just because we can use recursion to solve a problem, doesn't mean we should • For instance, we usually would not use recursion to solve the sum of 1 to N • The iterative version is easier to understand (in fact there is a formula that computes it without a loop at all) • You must be able to determine when recursion is the correct technique to use 8 - 15 Java Software Structures, 4th Edition, Lewis/Chase
  • 16. Recursion vs. Iteration • Every recursive solution has a corresponding iterative solution • A recursive solution may simply be less efficient • Furthermore, recursion has the overhead of multiple method invocations • However, for some problems recursive solutions are often more simple and elegant to express 8 - 16 Java Software Structures, 4th Edition, Lewis/Chase
  • 17. Factorial 4! = 4 * 3 * 2 * 1 n! = n * (n-1) * … * 1 4! = 4 * 3! n! = n * (n-1)! factorial(n) = n * factorial(n-1) //recursive step factorial(1) = 1 //base step PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 17 12/31/2022
  • 18. Method Factorial package myjava; import java.util.*; public class MyJava { public static int facto( int n ) { if(n == 1) //base step return (1); else //recursive step return(facto (n-1)*n); } public static void main (String args[]) { Scanner scan=new Scanner(System.in); System.out.println("enter any number :" ); int x = scan.nextInt(); System.out.println("the summation from 1 to " +x+ " = "+ facto( x )); } } PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 18 12/31/2022
  • 19. Fibonacci Sequence Numbers 0, 1, 1, 2, 3, 5, 8, 13, … Fib(n) = Fib(n-1) + Fib(n-2) // recursive step Fib(0) = 0 //base step Fib(1) = 1 //base step PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 19 12/31/2022
  • 20. Recursive Implementation of Fibonacci Numbers package myjava; import java.util.*; public class MyJava { public static int Fib(int n){ if(n<=1) return n; else return (Fib(n-1)+Fib(n-2)); } public static void main (String args[]) { int x =5; System.out.println("the Fib of " +x + " equal to "+ Fib( x ) ); } } PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 20 Fib(5) Fib(4) Fib(3) Fib(3) Fib(2) Fib(2) Fib(1) Fib(1) Fib(0) Fib(1) Fib(0) Fib(1) Fib(2) Fib(1) Fib(0) 5 1 0 1 1 2 1 1 0 1 0 1 1 3 2 12/31/2022
  • 21. End of Summer 2130 Java Software Structures, 4th Edition, Lewis/Chase 8 - 21
  • 22. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi Tower Of Hanoi • Goal: Move all disks from A to C • Rule: – No bigger disk is on top of smaller disk at any time – Move one disk at a time A B C 4 disks 12/31/2022 22
  • 23. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi Tower Of Hanoi • 1 disk moves from A to C: Simple! • 2 disks move from A to C A B C 2 disks 1 2 3 12/31/2022 23
  • 24. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi N disks from A to C? 1. Move n-1 disks from A to B 2. Move disk n from A to C 3. Move n-1 disks from B to C A B C disk n 1 n-1 disks 2 3 12/31/2022 24
  • 25. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 4-disk Example A B C 12/31/2022 25
  • 26. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 4-disk Example A B C 12/31/2022 26
  • 27. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 4-disk Example A B C 12/31/2022 27
  • 28. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi Recursive Code For Hanoi Tower (Trace of Recursive) package myjava; import java.util.*; public class MyJava { public static void move(int n, char start, char finish, char buf){ if(n==1) // stop condition: move one disk System.out.println("Move from " +start + " to "+ finish ); else{ move(n-1,start,buf,finish); // move n-1 from start to buf using //finish as temporary storage System.out.println("Move from " +start + " to "+ finish ); move(n-1,buf,finish,start); // move n-1 from buf to finish using //start as temporary storage }}; public static void main (String args[]) { move(3, 'A', 'C', 'B'); } } 12/31/2022 28
  • 29. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi Demo Of Hanoi • A nice animation of Hanoi online: – https://www.mathsisfun.com/games/ 12/31/2022 29
  • 30. Analyzing Recursive Algorithms • To determine the order of a loop, we determined the order of the body of the loop multiplied by the number of loop executions • Similarly, to determine the order of a recursive method, we determine the the order of the body of the method multiplied by the number of times the recursive method is called • In our recursive solution to compute the sum of integers from 1 to N, the method is invoked N times and the method itself is O(1) • So the order of the overall solution is O(n) 8 - 30 Java Software Structures, 4th Edition, Lewis/Chase
  • 31. Analyzing Recursive Algorithms • For the Towers of Hanoi puzzle, the step of moving one disk is O(1) • But each call results in calling itself twice more, so for N > 1, the growth function is f(n) = 2n – 1 • This is exponential efficiency: O(2n) • As the number of disks increases, the number of required moves increases exponentially 8 - 31 Java Software Structures, 4th Edition, Lewis/Chase