SlideShare a Scribd company logo
1 of 12
More on Recursion

  More techniques




                    1
Binary search algorithm
• Binary searching for a key in an array is similar to
  looking for a word in dictionary
• Take the midpoint of the dictionary and see if the
  key is in the lower half or upper half
• Pick the half the contains the key and take the
  midpoint of the half and see which quarter the
  key is in
• Repeat the above step until the key is matched or
  the dictionary cannot be halved any more
                                                     2
Use helper method
• Given int[] list and int key
• You are asked to return
   – the position of key in the array if matched or
   – -1 if not matched
• What additional information do you need to
  apply the algorithm above?



                                                      3
/** Use binary search to find the key in the list */
 public static int recursiveBinarySearch(int[] list, int key) {
  int low = 0;
  int high = list.length - 1;
  return recursiveBinarySearch(list, key, low, high); // use helper method
 }// recursiveBinarySearch method

/** Use binary search to find the key in the list between list[low] and list[high] */
 public static int recursiveBinarySearch(int[] list, int key, int low, int high)
 {
   if (low > high) // The list has been exhausted without a match
     return -1;

  int mid = (low + high) / 2;
  if (key < list[mid])
    return recursiveBinarySearch(list, key, low, mid - 1);
  else if (key == list[mid])
    return mid;
  else
    return recursiveBinarySearch(list, key, mid + 1, high);
 }// recursiveBinarySearch method
                                                                                        4
What is the difference between:
public static int recursiveBinarySearch(
        int[] list, int key){ . . . }
and
public static int recursiveBinarySearch(
        int[] list, int key, int low, int high) { . . . }
The first method calls the second method.
Is it recursive call?

                                                            5
Recursion versus iteration
Iteration                        Recursion
• Uses for or while loop for     • Recursion achieves
   repetition but no recursion     repetition without a loop
                                 • Price paid: memory
                                   overhead and run time
                                   (Every time a method is
                                   called, some space in
                                   memory must be reserved
                                   or allocated to
                                   store the method’s local
• Why use recursion?               variables and formal
                                   parameters, if any)

                                                               6
public class NestedCalls {
  public static void m1() {
     int m1_x = 1;
     int m1_y = 2;
     m2();                    // m1 calls m2
  } // m1 method

  public static void m2() {
     int m2_ = 3;
     int z = 4;
     z = m3();                //m2 calls m3
  }// m2 method

   public static int m3() {
      int m3_x =5;
      int m3_y = 6;
      return 1;
   }//m3 method
}//NestedCalls class
                                               7
Run NestedCalls.java with Bluej
         Debugger
    Observe the stack memory and
          calling sequences



                                   8
View of stack at various points of execution of
NestedCalls.java

                                            Stack frame for m3:
                                            m3_x:      5
                                            m3_y:      6
                      Stack frame for m2:   Stack frame for m2:
                      m2_x:      3          m2_x:      3
                      m2_z:       4         m2_z:       4
Stack frame for m1:   Stack frame for m1:   Stack frame for m1:
m1_x:       1         m1_x:       1         m1_x:       1
m1_y:       2         m1_y:       2         m1_y:       2


Just before           Just before           Just before m3
calling m2            calling m3            returns
                                                                  9
Stack of Binary Search just before returning from the
last recursive call




                                                        10
Why use recursion?

In some problems, iterative solutions are hard to
find.
But recursion is easy - See the Towers of Hanoi
problem in textbook. Animation by Michael Iverson




                                                    11
Other problems that are neatly solved by recursion:

Fractals:
• The Koch snowflake (demo)
• Sierpinski triangle (demo)




                                                      12

More Related Content

What's hot

This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...rapidbounce
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overridingJavaTportal
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Objective c runtime 分享2
Objective c runtime 分享2Objective c runtime 分享2
Objective c runtime 分享2Jeff Lee
 
한국어와 NLTK, Gensim의 만남
한국어와 NLTK, Gensim의 만남한국어와 NLTK, Gensim의 만남
한국어와 NLTK, Gensim의 만남Eunjeong (Lucy) Park
 
Missilecommand
MissilecommandMissilecommand
MissilecommandSusan Gold
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting StartedHadziq Fabroyir
 
ML2014_Poster_ TextClusteringDemo
ML2014_Poster_ TextClusteringDemoML2014_Poster_ TextClusteringDemo
ML2014_Poster_ TextClusteringDemoGeorge Simov
 

What's hot (16)

This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...This presentation is a great introduction to both fundamental programming con...
This presentation is a great introduction to both fundamental programming con...
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Objective c runtime 分享2
Objective c runtime 分享2Objective c runtime 分享2
Objective c runtime 分享2
 
Oech03
Oech03Oech03
Oech03
 
한국어와 NLTK, Gensim의 만남
한국어와 NLTK, Gensim의 만남한국어와 NLTK, Gensim의 만남
한국어와 NLTK, Gensim의 만남
 
Missilecommand
MissilecommandMissilecommand
Missilecommand
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
Lect9
Lect9Lect9
Lect9
 
ML2014_Poster_ TextClusteringDemo
ML2014_Poster_ TextClusteringDemoML2014_Poster_ TextClusteringDemo
ML2014_Poster_ TextClusteringDemo
 
SOLID
 SOLID SOLID
SOLID
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
 
C++ assignment
C++ assignmentC++ assignment
C++ assignment
 

Viewers also liked

Week11
Week11Week11
Week11hccit
 
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitzFundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitzJAKEwook
 
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 KATARIADheeraj Kataria
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and loopingxcoolanurag
 

Viewers also liked (7)

Week11
Week11Week11
Week11
 
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitzFundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
 
Recursion
RecursionRecursion
Recursion
 
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
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
Recursion
RecursionRecursion
Recursion
 
Recursion
RecursionRecursion
Recursion
 

Similar to 4 recursion details

Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts S Akai
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 
Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||datt30
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessIgor Sfiligoi
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrqlmsg systems ag
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - InheritanceOum Saokosal
 
CS3491-AI and ML lab manual cs3491 r2021
CS3491-AI and ML lab manual    cs3491 r2021CS3491-AI and ML lab manual    cs3491 r2021
CS3491-AI and ML lab manual cs3491 r2021parvathy Mookambiga
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and FunctionRatnaJava
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxAbuHuraira729502
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptxajajkhan16
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkSerge Stinckwich
 
ML Module 3 Non Linear Learning.pptx
ML Module 3 Non Linear Learning.pptxML Module 3 Non Linear Learning.pptx
ML Module 3 Non Linear Learning.pptxDebabrataPain1
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16Max Kleiner
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questionsgokul174578
 

Similar to 4 recursion details (20)

Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts
 
FUNDAMETAL ALG.ppt
FUNDAMETAL ALG.pptFUNDAMETAL ALG.ppt
FUNDAMETAL ALG.ppt
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrql
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
CS3491-AI and ML lab manual cs3491 r2021
CS3491-AI and ML lab manual    cs3491 r2021CS3491-AI and ML lab manual    cs3491 r2021
CS3491-AI and ML lab manual cs3491 r2021
 
Learn Terraform - Variables
Learn Terraform - VariablesLearn Terraform - Variables
Learn Terraform - Variables
 
Data Handling and Function
Data Handling and FunctionData Handling and Function
Data Handling and Function
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptx
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
ML Module 3 Non Linear Learning.pptx
ML Module 3 Non Linear Learning.pptxML Module 3 Non Linear Learning.pptx
ML Module 3 Non Linear Learning.pptx
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
A closure ekon16
A closure ekon16A closure ekon16
A closure ekon16
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
 

More from Abhijit Gaikwad (11)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
17 sessions
17 sessions17 sessions
17 sessions
 
16 cookies
16 cookies16 cookies
16 cookies
 
15 decorator pattern
15 decorator pattern15 decorator pattern
15 decorator pattern
 
12 memory hierarchy
12 memory hierarchy12 memory hierarchy
12 memory hierarchy
 
12 cache questions
12 cache questions12 cache questions
12 cache questions
 
10 strategy pattern
10 strategy pattern10 strategy pattern
10 strategy pattern
 
9 abstract interface
9 abstract interface9 abstract interface
9 abstract interface
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
7 inheritance
7 inheritance7 inheritance
7 inheritance
 

4 recursion details

  • 1. More on Recursion More techniques 1
  • 2. Binary search algorithm • Binary searching for a key in an array is similar to looking for a word in dictionary • Take the midpoint of the dictionary and see if the key is in the lower half or upper half • Pick the half the contains the key and take the midpoint of the half and see which quarter the key is in • Repeat the above step until the key is matched or the dictionary cannot be halved any more 2
  • 3. Use helper method • Given int[] list and int key • You are asked to return – the position of key in the array if matched or – -1 if not matched • What additional information do you need to apply the algorithm above? 3
  • 4. /** Use binary search to find the key in the list */ public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return recursiveBinarySearch(list, key, low, high); // use helper method }// recursiveBinarySearch method /** Use binary search to find the key in the list between list[low] and list[high] */ public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -1; int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }// recursiveBinarySearch method 4
  • 5. What is the difference between: public static int recursiveBinarySearch( int[] list, int key){ . . . } and public static int recursiveBinarySearch( int[] list, int key, int low, int high) { . . . } The first method calls the second method. Is it recursive call? 5
  • 6. Recursion versus iteration Iteration Recursion • Uses for or while loop for • Recursion achieves repetition but no recursion repetition without a loop • Price paid: memory overhead and run time (Every time a method is called, some space in memory must be reserved or allocated to store the method’s local • Why use recursion? variables and formal parameters, if any) 6
  • 7. public class NestedCalls { public static void m1() { int m1_x = 1; int m1_y = 2; m2(); // m1 calls m2 } // m1 method public static void m2() { int m2_ = 3; int z = 4; z = m3(); //m2 calls m3 }// m2 method public static int m3() { int m3_x =5; int m3_y = 6; return 1; }//m3 method }//NestedCalls class 7
  • 8. Run NestedCalls.java with Bluej Debugger Observe the stack memory and calling sequences 8
  • 9. View of stack at various points of execution of NestedCalls.java Stack frame for m3: m3_x: 5 m3_y: 6 Stack frame for m2: Stack frame for m2: m2_x: 3 m2_x: 3 m2_z: 4 m2_z: 4 Stack frame for m1: Stack frame for m1: Stack frame for m1: m1_x: 1 m1_x: 1 m1_x: 1 m1_y: 2 m1_y: 2 m1_y: 2 Just before Just before Just before m3 calling m2 calling m3 returns 9
  • 10. Stack of Binary Search just before returning from the last recursive call 10
  • 11. Why use recursion? In some problems, iterative solutions are hard to find. But recursion is easy - See the Towers of Hanoi problem in textbook. Animation by Michael Iverson 11
  • 12. Other problems that are neatly solved by recursion: Fractals: • The Koch snowflake (demo) • Sierpinski triangle (demo) 12