SlideShare a Scribd company logo
Data Structures and Algorithms in Java
3. Recursion
1/25
Data Structures and Algorithms in Java
Objectives
• Recursive definition
• Recursive program/algorithm
• Recursion application
• Method calls and recursion implementation
• Anatomy of a recursive call
• Classify recursions by number of recursive calls
• Tail recursion
• Non-tail recursion
• Indirect recursion
• Nested recursion
• Excessive recursion
2/25
Data Structures and Algorithms in Java
Recursive definition
• Wikipedia: “A recursive definition or inductive definition is one that
defines something in terms of itself (that is, recursively). For it to
work, the definition in any given case must be well-founded,
avoiding an infinite regress”.
• A recursive definition consists of at least 2 parts:
1) A base case (anchor or the ground case) that does not contain a
reference to its own type.
2) An inductive case that does contain a reference to its own type.
For example: Define the set of natural numbers
N
set
the
in
objects
other
no
are
there
N
n
then
N
n
if
N
.
3
)
1
(
,
.
2
0
.
1




3/25
Data Structures and Algorithms in Java
Some other examples for recursive definition
1 if n = 0 (anchor)
n*(n-1)! if n>0 (inductive step)
n! =
• The Fibonacci sequence of natural numbers:
n if n<2
fibo(n-1) +fibo(n-2) otherwise
fibo(n) =
• The Factorial of a natural number:
4/25
Data Structures and Algorithms in Java 5/27
Recursive program/algorithm - 1
One way to describe repetition within a computer program is the
use of loops, such as Java’s while-loop and for-loop constructs. An
entirely different way to achieve repetition is through a process
known as recursion. Recursion is a technique by which a method
makes one or more calls to itself during execution, or by which a
data structure relies upon smaller instances of the very same type
of structure in its representation. In computing, recursion provides
an elegant and powerful alternative for performing repetitive tasks.
Most modern programming languages support functional recursion
using the identical mechanism that is used to support traditional
forms of method calls. When one invocation of the method makes a
recursive call, that invocation is suspended until the recursive call
completes. Recursion is an important technique in the study of data
structures and algorithms.
Data Structures and Algorithms in Java 6/27
Recursive program/algorithm - 2
A recursive program/algorithm is one that calls itself again.
There are three basic rules for developing recursive algorithms.
• Know how to take one step.
• Break each problem down into one step plus a smaller
problem.
• Know how and when to stop.
Example for recursive program:
public static void DecToBin(int n)
{ int q = n/2; // One step
int r = n%2; // One step
if (q > 0)
{DecToBin(q); // smaller problem
}
System.out.print(r); // after all recursive calls have been
// made last remainder printed first
}
Data Structures and Algorithms in Java 7/27
Recursion application
• Recursive definitions are used in defining
functions or sequences of elements
• Purpose of recursive definition:
– Generating a new elements
– Testing whether an element belongs to a set (*)
• (*) The problem is solved by reducing it to a
simpler problem
Data Structures and Algorithms in Java 8/27
Method calls and recursion implementation - 1
Each time a method is called, an activation record (AR) is allocated for it.
This record usually contains the following information:
• Parameters and local variables used in the called method.
• A dynamic link, which is a pointer to the caller's activation record.
• Return address to resume control by the caller, the address of the
caller’s instruction immediately following the call.
• Return value for a method not declared as void. Because the size of the
activation record may vary from one call to another, the returned value is
placed right above the activation record of the caller.
Each new activation record is placed on the top of the run-time stack
When a method terminates, its activation record is removed from the top
of the run-time stack
Thus, the first AR placed onto the stack is the last one removed
Data Structures and Algorithms in Java 9/27
Creating an activation record whenever a method is
called allows the system to handle recursion
properly. Recursion is calling a method that happens
to have the same name as the caller. Therefore, a
recursive call is not literally a method calling it-self,
but rather an instantiation of a method calling
another instantiation of the same original. These
invocation are represented internally by different
activation records and are thus differentiated by the
system.
Method calls and recursion implementation - 2
Data Structures and Algorithms in Java 10/27
Anatomy of a recursive Call
N = 4
N <= 1? NO
return (4 * factorial (3)) =
N = 3
N <= 1? NO
return (3 * factorial (2)) =
N = 2
N <= 1? NO
return (2 * factorial (1)) =
N = 1
N <= 1? YES
Return (1)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
2
6
24
1
1
2
6
24
First call
Data Structures and Algorithms in Java 11/27
Classification of recursive functions by number
of recursive calls
Considering the maximum number of recursive calls
within the body of a single activation, there are 3 types
of recursions.
• Linear recursion: Only 1 recursive call (to itself) in side
the recursive function (e.g. binary search).
• Binary recursion: There exactly 2 recursive calls (to
itself) in side the recursive function (e.g. Fibonacci
number) .
• Multiple recursion: There are 3 or more recursive calls
(to itself) in side the recursive function.
Data Structures and Algorithms in Java 12/27
Tail recursion
• There is only one recursive call at the very end
of a method implementation
Other classification of recursions
class Main
{static void tail(int n)
{if(n >0)
{ System.out.print(n + " ");
tail(n-1);
}
}
public static void main(String [] args)
{tail(10);
System.out.println();
}
}
void nonTail (int i)
{ if (i > 0)
{tail(i-1);
System.out.print (i + "");
tail(i-1);
}
}
Data Structures and Algorithms in Java 13/27
Non-tail recursion
• The recursive call is not at the very end of a method
implementation
public class Main
{public static void reverse() throws Exception
{char ch = (char) System.in.read();
if(ch != 'n')
{reverse();
System.out.print(ch);
}
}
public static void main(String [] args) throws Exception
{System.out.println("nEnter a string to be reversed:");
reverse();
System.out.println("n");
}
}
Data Structures and Algorithms in Java 14/27
Convert recursion implementation
to iterative implementation using stack
{public static void nonRecursiveReverse() throws Exception
{MyStack t = new MyStack();
char ch;
while(true)
{ch = (char) System.in.read();
if(ch == 'n') break;
t.push(ch);
}
while(!t.isEmpty())
System.out.print(t.pop());
}
Data Structures and Algorithms in Java 15/27
Indirect recursion
• If f() calls itself, it is direct recursive
• If f() calls g(), and g() calls f(). It is indirect recursion. The chain of
intermediate calls can be of an arbitrary length, as in:
f() -> f1() -> f2() -> ... -> fn() -> f()
• Example: sin(x) calculation
Recursive call tree for sin(x)
sin(x)
sin(x/3) tan(x/3) tan(x/3)
sin(x/3) cos(x/3) sin(x/3) cos(x)
sin(x/6) sin(x/6)
Data Structures and Algorithms in Java 16/27
Nested recursion
• A function is not only defined in terms of itself but also is
used as one of the parameters
• Consider the following examples:
0 if n=0
n if n>4
h(2 +h(2n)) if n<=4
Another example of nested recursive recursion is
Ackermann’s function:
A(0, y) = y + 1
A(x, 0) = A(x - 1, 1)
A(x, y) = A(x - 1, A(x, y - 1))
h(n) =
This function is interesting because of
its remarkably rapid growth.
A(3,1) = 24 - 3
A(4,1) = 265536 - 3
Data Structures and Algorithms in Java 17/27
Excessive recursion - 1
• Consider the Fibonacci sequence of numbers
n if n<2
fibo(n-1) +fibo(n-2) otherwise
static long fibo(long n)
{if (n<2)
return n;
else
return(fibo(n-1)+fibo(n-2));
}
This
implementation
looks very natural
but extremely
inefficient!
fibo(n) =
Data Structures and Algorithms in Java 18/27
The tree of calls for fibo(4)
18
Fib(4)
Fib(2) Fib(3)
Fib(0) Fib(1)
1
0
Fib(2)
Fib(0) Fib(1)
1
0
Fib(1)
1
Excessive recursion - 2
Data Structures and Algorithms in Java 19/27
More Examples – The Tower of Hanoi
19
• Rules:
Only one disk may be moved at a time.
Each move consists of taking the upper disk from one
of the rods and sliding it onto another rod, on top of
the other disks that may already be present on that
rod.
No disk may be placed on top of a smaller disk.
Source: http://en.wikipedia.org/wiki/Hanoi_tower
Data Structures and Algorithms in Java 20/27
More Examples – The Tower of Hanoi
Algorithm
20
void moveDisks(int n, char fromTower, char toTower, char auxTower)
{if (n == 1) // Stopping condition
Move disk 1 from the fromTower to the toTower;
else
{moveDisks(n - 1, fromTower, auxTower, toTower);
move disk n from the fromTower to the toTower;
moveDisks(n - 1, auxTower, toTower, fromTower);
}
}
Data Structures and Algorithms in Java 21/27
More Examples – Drawing fractals
21
Data Structures and Algorithms in Java 22/27
1. Divide an interval side into three even parts
2. Move one-third of side in the direction
specified by angle
Examples of von Koch snowflakes
More Examples – Von Knoch snowflakes
Data Structures and Algorithms in Java 23/27
Recursion vs. Iteration
23
• Some recursive algorithms can also be easily
implemented with loops
– When possible, it is usually better to use iteration,
since we don’t have the overhead of the run-time stack
(that we just saw on the previous slide)
• Other recursive algorithms are very difficult to
do any other way
Data Structures and Algorithms in Java 24/27
Summary
• Recursive definitions are programming concepts that
define themselves
• Recursive definitions serve two purposes:
– Generating new elements
– Testing whether an element belongs to a set
• Recursive definitions are frequently used to define
functions and sequences of numbers
• Tail recursion is characterized by the use of only one
recursive call at the very end of a method
implementation.
Data Structures and Algorithms in Java 25/25
Reading at home
Text book: Data Structures and Algorithms in Java
5 Recursion 189
5.1 Illustrative Examples - 191
5.1.1 The Factorial Function -191
5.1.3 Binary Search - 196
5.1.4 File Systems - 198
5.2 Analyzing Recursive Algorithms - 202
5.3 Further Examples of Recursion - 206
5.3.1 Linear Recursion - 206
5.3.2 Binary Recursion - . 211
5.3.3 Multiple Recursion - 212
5.4 Designing Recursive Algorithms - 214
5.6 Eliminating Tail Recursion -. 219

More Related Content

What's hot

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
xcoolanurag
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of Algorithms
Krishnan MuthuManickam
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
Hanif Durad
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
Hanif Durad
 
Recursion
RecursionRecursion
Recursion
Malainine Zaid
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
Venkatesh Iyer
 
Chapter 10 ds
Chapter 10 dsChapter 10 ds
Chapter 10 ds
Hanif Durad
 
Chapter 2 ds
Chapter 2 dsChapter 2 ds
Chapter 2 ds
Hanif Durad
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
ManishPrajapati78
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
Mohammed Hussein
 
Recursion
RecursionRecursion
Recursion
Ssankett Negi
 
Algorithm & data structure lec2
Algorithm & data structure lec2Algorithm & data structure lec2
Algorithm & data structure lec2
Abdul Khan
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
ashish bansal
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
Pratik Mota
 
Design & Analysis Of Algorithm
Design & Analysis Of AlgorithmDesign & Analysis Of Algorithm
Design & Analysis Of Algorithm
Computer Hardware & Trouble shooting
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
Aniruddha Paul
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
FALLEE31188
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main Concepts
Adelina Ahadova
 

What's hot (20)

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of Algorithms
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
Recursion
RecursionRecursion
Recursion
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Chapter 10 ds
Chapter 10 dsChapter 10 ds
Chapter 10 ds
 
Chapter 2 ds
Chapter 2 dsChapter 2 ds
Chapter 2 ds
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
 
Recursion
RecursionRecursion
Recursion
 
Algorithm & data structure lec2
Algorithm & data structure lec2Algorithm & data structure lec2
Algorithm & data structure lec2
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
 
Design & Analysis Of Algorithm
Design & Analysis Of AlgorithmDesign & Analysis Of Algorithm
Design & Analysis Of Algorithm
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main Concepts
 

Similar to 3 recursion

Ppt chapter12
Ppt chapter12Ppt chapter12
Ppt chapter12
Richard Styner
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
skilljiolms
 
Recursion in Data Structure
Recursion in Data StructureRecursion in Data Structure
Recursion in Data Structure
khudabux1998
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
ajajkhan16
 
Introduction to deep learning
Introduction to deep learningIntroduction to deep learning
Introduction to deep learning
Junaid Bhat
 
R Basics
R BasicsR Basics
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
Narayan Sau
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
Jabs6
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
Chikugehlot
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
Arumugam90
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
Shaili Choudhary
 
DATA STRUCTURES unit 1.pptx
DATA STRUCTURES unit 1.pptxDATA STRUCTURES unit 1.pptx
DATA STRUCTURES unit 1.pptx
ShivamKrPathak
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Programming in python
Programming in pythonProgramming in python
Programming in python
Ivan Rojas
 
Machine Learning Algorithms (Part 1)
Machine Learning Algorithms (Part 1)Machine Learning Algorithms (Part 1)
Machine Learning Algorithms (Part 1)
Zihui Li
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
University of Gujrat, Pakistan
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
gilvalerio
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
omair31
 

Similar to 3 recursion (20)

Ppt chapter12
Ppt chapter12Ppt chapter12
Ppt chapter12
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
 
Recursion in Data Structure
Recursion in Data StructureRecursion in Data Structure
Recursion in Data Structure
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
 
Introduction to deep learning
Introduction to deep learningIntroduction to deep learning
Introduction to deep learning
 
R Basics
R BasicsR Basics
R Basics
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
DATA STRUCTURES unit 1.pptx
DATA STRUCTURES unit 1.pptxDATA STRUCTURES unit 1.pptx
DATA STRUCTURES unit 1.pptx
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Programming in python
Programming in pythonProgramming in python
Programming in python
 
Machine Learning Algorithms (Part 1)
Machine Learning Algorithms (Part 1)Machine Learning Algorithms (Part 1)
Machine Learning Algorithms (Part 1)
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
 

Recently uploaded

Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
AbdullaAlAsif1
 
The debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically youngThe debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically young
Sérgio Sacani
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
Abdul Wali Khan University Mardan,kP,Pakistan
 
Eukaryotic Transcription Presentation.pptx
Eukaryotic Transcription Presentation.pptxEukaryotic Transcription Presentation.pptx
Eukaryotic Transcription Presentation.pptx
RitabrataSarkar3
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
Gokturk Mehmet Dilci
 
Deep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless ReproducibilityDeep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless Reproducibility
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Immersive Learning That Works: Research Grounding and Paths Forward
Immersive Learning That Works: Research Grounding and Paths ForwardImmersive Learning That Works: Research Grounding and Paths Forward
Immersive Learning That Works: Research Grounding and Paths Forward
Leonel Morgado
 
molar-distalization in orthodontics-seminar.pptx
molar-distalization in orthodontics-seminar.pptxmolar-distalization in orthodontics-seminar.pptx
molar-distalization in orthodontics-seminar.pptx
Anagha Prasad
 
Oedema_types_causes_pathophysiology.pptx
Oedema_types_causes_pathophysiology.pptxOedema_types_causes_pathophysiology.pptx
Oedema_types_causes_pathophysiology.pptx
muralinath2
 
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
vluwdy49
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
PRIYANKA PATEL
 
Thornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdfThornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdf
European Sustainable Phosphorus Platform
 
Medical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptxMedical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptx
terusbelajar5
 
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
Sérgio Sacani
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills MN
 
aziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobelaziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobel
İsa Badur
 
20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx
Sharon Liu
 
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptxThe use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
MAGOTI ERNEST
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
David Osipyan
 
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdfwaterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
LengamoLAppostilic
 

Recently uploaded (20)

Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
 
The debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically youngThe debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically young
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
 
Eukaryotic Transcription Presentation.pptx
Eukaryotic Transcription Presentation.pptxEukaryotic Transcription Presentation.pptx
Eukaryotic Transcription Presentation.pptx
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
 
Deep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless ReproducibilityDeep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless Reproducibility
 
Immersive Learning That Works: Research Grounding and Paths Forward
Immersive Learning That Works: Research Grounding and Paths ForwardImmersive Learning That Works: Research Grounding and Paths Forward
Immersive Learning That Works: Research Grounding and Paths Forward
 
molar-distalization in orthodontics-seminar.pptx
molar-distalization in orthodontics-seminar.pptxmolar-distalization in orthodontics-seminar.pptx
molar-distalization in orthodontics-seminar.pptx
 
Oedema_types_causes_pathophysiology.pptx
Oedema_types_causes_pathophysiology.pptxOedema_types_causes_pathophysiology.pptx
Oedema_types_causes_pathophysiology.pptx
 
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
 
Thornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdfThornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdf
 
Medical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptxMedical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptx
 
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
EWOCS-I: The catalog of X-ray sources in Westerlund 1 from the Extended Weste...
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
 
aziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobelaziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobel
 
20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx
 
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptxThe use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
 
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdfwaterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
 

3 recursion

  • 1. Data Structures and Algorithms in Java 3. Recursion 1/25
  • 2. Data Structures and Algorithms in Java Objectives • Recursive definition • Recursive program/algorithm • Recursion application • Method calls and recursion implementation • Anatomy of a recursive call • Classify recursions by number of recursive calls • Tail recursion • Non-tail recursion • Indirect recursion • Nested recursion • Excessive recursion 2/25
  • 3. Data Structures and Algorithms in Java Recursive definition • Wikipedia: “A recursive definition or inductive definition is one that defines something in terms of itself (that is, recursively). For it to work, the definition in any given case must be well-founded, avoiding an infinite regress”. • A recursive definition consists of at least 2 parts: 1) A base case (anchor or the ground case) that does not contain a reference to its own type. 2) An inductive case that does contain a reference to its own type. For example: Define the set of natural numbers N set the in objects other no are there N n then N n if N . 3 ) 1 ( , . 2 0 . 1     3/25
  • 4. Data Structures and Algorithms in Java Some other examples for recursive definition 1 if n = 0 (anchor) n*(n-1)! if n>0 (inductive step) n! = • The Fibonacci sequence of natural numbers: n if n<2 fibo(n-1) +fibo(n-2) otherwise fibo(n) = • The Factorial of a natural number: 4/25
  • 5. Data Structures and Algorithms in Java 5/27 Recursive program/algorithm - 1 One way to describe repetition within a computer program is the use of loops, such as Java’s while-loop and for-loop constructs. An entirely different way to achieve repetition is through a process known as recursion. Recursion is a technique by which a method makes one or more calls to itself during execution, or by which a data structure relies upon smaller instances of the very same type of structure in its representation. In computing, recursion provides an elegant and powerful alternative for performing repetitive tasks. Most modern programming languages support functional recursion using the identical mechanism that is used to support traditional forms of method calls. When one invocation of the method makes a recursive call, that invocation is suspended until the recursive call completes. Recursion is an important technique in the study of data structures and algorithms.
  • 6. Data Structures and Algorithms in Java 6/27 Recursive program/algorithm - 2 A recursive program/algorithm is one that calls itself again. There are three basic rules for developing recursive algorithms. • Know how to take one step. • Break each problem down into one step plus a smaller problem. • Know how and when to stop. Example for recursive program: public static void DecToBin(int n) { int q = n/2; // One step int r = n%2; // One step if (q > 0) {DecToBin(q); // smaller problem } System.out.print(r); // after all recursive calls have been // made last remainder printed first }
  • 7. Data Structures and Algorithms in Java 7/27 Recursion application • Recursive definitions are used in defining functions or sequences of elements • Purpose of recursive definition: – Generating a new elements – Testing whether an element belongs to a set (*) • (*) The problem is solved by reducing it to a simpler problem
  • 8. Data Structures and Algorithms in Java 8/27 Method calls and recursion implementation - 1 Each time a method is called, an activation record (AR) is allocated for it. This record usually contains the following information: • Parameters and local variables used in the called method. • A dynamic link, which is a pointer to the caller's activation record. • Return address to resume control by the caller, the address of the caller’s instruction immediately following the call. • Return value for a method not declared as void. Because the size of the activation record may vary from one call to another, the returned value is placed right above the activation record of the caller. Each new activation record is placed on the top of the run-time stack When a method terminates, its activation record is removed from the top of the run-time stack Thus, the first AR placed onto the stack is the last one removed
  • 9. Data Structures and Algorithms in Java 9/27 Creating an activation record whenever a method is called allows the system to handle recursion properly. Recursion is calling a method that happens to have the same name as the caller. Therefore, a recursive call is not literally a method calling it-self, but rather an instantiation of a method calling another instantiation of the same original. These invocation are represented internally by different activation records and are thus differentiated by the system. Method calls and recursion implementation - 2
  • 10. Data Structures and Algorithms in Java 10/27 Anatomy of a recursive Call N = 4 N <= 1? NO return (4 * factorial (3)) = N = 3 N <= 1? NO return (3 * factorial (2)) = N = 2 N <= 1? NO return (2 * factorial (1)) = N = 1 N <= 1? YES Return (1) factorial(4) factorial(3) factorial(2) factorial(1) 2 6 24 1 1 2 6 24 First call
  • 11. Data Structures and Algorithms in Java 11/27 Classification of recursive functions by number of recursive calls Considering the maximum number of recursive calls within the body of a single activation, there are 3 types of recursions. • Linear recursion: Only 1 recursive call (to itself) in side the recursive function (e.g. binary search). • Binary recursion: There exactly 2 recursive calls (to itself) in side the recursive function (e.g. Fibonacci number) . • Multiple recursion: There are 3 or more recursive calls (to itself) in side the recursive function.
  • 12. Data Structures and Algorithms in Java 12/27 Tail recursion • There is only one recursive call at the very end of a method implementation Other classification of recursions class Main {static void tail(int n) {if(n >0) { System.out.print(n + " "); tail(n-1); } } public static void main(String [] args) {tail(10); System.out.println(); } } void nonTail (int i) { if (i > 0) {tail(i-1); System.out.print (i + ""); tail(i-1); } }
  • 13. Data Structures and Algorithms in Java 13/27 Non-tail recursion • The recursive call is not at the very end of a method implementation public class Main {public static void reverse() throws Exception {char ch = (char) System.in.read(); if(ch != 'n') {reverse(); System.out.print(ch); } } public static void main(String [] args) throws Exception {System.out.println("nEnter a string to be reversed:"); reverse(); System.out.println("n"); } }
  • 14. Data Structures and Algorithms in Java 14/27 Convert recursion implementation to iterative implementation using stack {public static void nonRecursiveReverse() throws Exception {MyStack t = new MyStack(); char ch; while(true) {ch = (char) System.in.read(); if(ch == 'n') break; t.push(ch); } while(!t.isEmpty()) System.out.print(t.pop()); }
  • 15. Data Structures and Algorithms in Java 15/27 Indirect recursion • If f() calls itself, it is direct recursive • If f() calls g(), and g() calls f(). It is indirect recursion. The chain of intermediate calls can be of an arbitrary length, as in: f() -> f1() -> f2() -> ... -> fn() -> f() • Example: sin(x) calculation Recursive call tree for sin(x) sin(x) sin(x/3) tan(x/3) tan(x/3) sin(x/3) cos(x/3) sin(x/3) cos(x) sin(x/6) sin(x/6)
  • 16. Data Structures and Algorithms in Java 16/27 Nested recursion • A function is not only defined in terms of itself but also is used as one of the parameters • Consider the following examples: 0 if n=0 n if n>4 h(2 +h(2n)) if n<=4 Another example of nested recursive recursion is Ackermann’s function: A(0, y) = y + 1 A(x, 0) = A(x - 1, 1) A(x, y) = A(x - 1, A(x, y - 1)) h(n) = This function is interesting because of its remarkably rapid growth. A(3,1) = 24 - 3 A(4,1) = 265536 - 3
  • 17. Data Structures and Algorithms in Java 17/27 Excessive recursion - 1 • Consider the Fibonacci sequence of numbers n if n<2 fibo(n-1) +fibo(n-2) otherwise static long fibo(long n) {if (n<2) return n; else return(fibo(n-1)+fibo(n-2)); } This implementation looks very natural but extremely inefficient! fibo(n) =
  • 18. Data Structures and Algorithms in Java 18/27 The tree of calls for fibo(4) 18 Fib(4) Fib(2) Fib(3) Fib(0) Fib(1) 1 0 Fib(2) Fib(0) Fib(1) 1 0 Fib(1) 1 Excessive recursion - 2
  • 19. Data Structures and Algorithms in Java 19/27 More Examples – The Tower of Hanoi 19 • Rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk. Source: http://en.wikipedia.org/wiki/Hanoi_tower
  • 20. Data Structures and Algorithms in Java 20/27 More Examples – The Tower of Hanoi Algorithm 20 void moveDisks(int n, char fromTower, char toTower, char auxTower) {if (n == 1) // Stopping condition Move disk 1 from the fromTower to the toTower; else {moveDisks(n - 1, fromTower, auxTower, toTower); move disk n from the fromTower to the toTower; moveDisks(n - 1, auxTower, toTower, fromTower); } }
  • 21. Data Structures and Algorithms in Java 21/27 More Examples – Drawing fractals 21
  • 22. Data Structures and Algorithms in Java 22/27 1. Divide an interval side into three even parts 2. Move one-third of side in the direction specified by angle Examples of von Koch snowflakes More Examples – Von Knoch snowflakes
  • 23. Data Structures and Algorithms in Java 23/27 Recursion vs. Iteration 23 • Some recursive algorithms can also be easily implemented with loops – When possible, it is usually better to use iteration, since we don’t have the overhead of the run-time stack (that we just saw on the previous slide) • Other recursive algorithms are very difficult to do any other way
  • 24. Data Structures and Algorithms in Java 24/27 Summary • Recursive definitions are programming concepts that define themselves • Recursive definitions serve two purposes: – Generating new elements – Testing whether an element belongs to a set • Recursive definitions are frequently used to define functions and sequences of numbers • Tail recursion is characterized by the use of only one recursive call at the very end of a method implementation.
  • 25. Data Structures and Algorithms in Java 25/25 Reading at home Text book: Data Structures and Algorithms in Java 5 Recursion 189 5.1 Illustrative Examples - 191 5.1.1 The Factorial Function -191 5.1.3 Binary Search - 196 5.1.4 File Systems - 198 5.2 Analyzing Recursive Algorithms - 202 5.3 Further Examples of Recursion - 206 5.3.1 Linear Recursion - 206 5.3.2 Binary Recursion - . 211 5.3.3 Multiple Recursion - 212 5.4 Designing Recursive Algorithms - 214 5.6 Eliminating Tail Recursion -. 219