ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
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
   ¨C the position of key in the array if matched or
   ¨C -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 snow?ake (demo)
? Sierpinski triangle (demo)




                                                      12

More Related Content

What's hot (16)

PPTX
This presentation is a great introduction to both fundamental programming con...
rapidbounce
?
PPT
Polymorphism in java, method overloading and method overriding
JavaTportal
?
PDF
Learn a language : LISP
Devnology
?
PPT
Runnable interface.34
myrajendra
?
PDF
Objective c runtime ·ÖÏí2
Jeff Lee
?
PDF
Oech03
fangjiafu
?
PDF
???? NLTK, Gensim? ??
Eunjeong (Lucy) Park
?
PDF
Missilecommand
Susan Gold
?
PDF
C sharp chap6
Mukesh Tekwani
?
PPTX
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
?
PPTX
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
?
PPTX
ML2014_Poster_ TextClusteringDemo
George Simov
?
PPTX
Thread priorities
Then Murugeshwari
?
DOCX
C++ assignment
vishnuvardhan221292
?
This presentation is a great introduction to both fundamental programming con...
rapidbounce
?
Polymorphism in java, method overloading and method overriding
JavaTportal
?
Learn a language : LISP
Devnology
?
Runnable interface.34
myrajendra
?
Objective c runtime ·ÖÏí2
Jeff Lee
?
Oech03
fangjiafu
?
???? NLTK, Gensim? ??
Eunjeong (Lucy) Park
?
Missilecommand
Susan Gold
?
C sharp chap6
Mukesh Tekwani
?
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
?
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
?
ML2014_Poster_ TextClusteringDemo
George Simov
?
Thread priorities
Then Murugeshwari
?
C++ assignment
vishnuvardhan221292
?

Viewers also liked (7)

PDF
Week11
hccit
?
PDF
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
JAKEwook
?
PPTX
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
?
PPT
Recursion and looping
xcoolanurag
?
PPTX
Recursion
Asif Ali Raza
?
PPT
Recursion
grahamwell
?
Week11
hccit
?
Fundamentals of data structure in c s. sahni , s. anderson freed and e. horowitz
JAKEwook
?
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
?
Recursion and looping
xcoolanurag
?
Recursion
Asif Ali Raza
?
Recursion
grahamwell
?
Ad

Similar to 4 recursion details (20)

PPT
3-Recursion.ppt
TrnHuy921814
?
PPT
3 recursion
Nguync91368
?
PPT
Cis068 08
FALLEE31188
?
PDF
ARM procedure calling conventions and recursion
Stephan Cadene
?
PDF
Garbage
minhngoc233
?
PPT
FUNDAMETAL ALG.ppt
Menaka Sivakumar
?
PDF
Programming in Java: Recursion
Martin Chapman
?
PDF
Java Pitfalls and Good-to-Knows
Miquel Martin
?
PDF
Sure interview algorithm-1103
Sure Interview
?
PPTX
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
garbervetsky
?
PPT
Chap14
Terry Yoast
?
PPT
Data Structures- Part5 recursion
Abdullah Al-hazmy
?
PPT
Ap Power Point Chpt8
dplunkett
?
PPT
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
?
PPTX
Recursion is used in programming languages to use a procedure multiple times ...
najiyanasrink
?
PPT
BST.ppt
DEEPAK948083
?
3-Recursion.ppt
TrnHuy921814
?
3 recursion
Nguync91368
?
Cis068 08
FALLEE31188
?
ARM procedure calling conventions and recursion
Stephan Cadene
?
Garbage
minhngoc233
?
FUNDAMETAL ALG.ppt
Menaka Sivakumar
?
Programming in Java: Recursion
Martin Chapman
?
Java Pitfalls and Good-to-Knows
Miquel Martin
?
Sure interview algorithm-1103
Sure Interview
?
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
garbervetsky
?
Data Structures- Part5 recursion
Abdullah Al-hazmy
?
Ap Power Point Chpt8
dplunkett
?
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
?
Recursion is used in programming languages to use a procedure multiple times ...
najiyanasrink
?
BST.ppt
DEEPAK948083
?
Ad

More from Abhijit Gaikwad (11)

PDF
Java concurrency
Abhijit Gaikwad
?
PPT
20 ch22 collections
Abhijit Gaikwad
?
PPT
17 sessions
Abhijit Gaikwad
?
PPT
16 cookies
Abhijit Gaikwad
?
PPT
15 decorator pattern
Abhijit Gaikwad
?
PPT
12 memory hierarchy
Abhijit Gaikwad
?
PPT
12 cache questions
Abhijit Gaikwad
?
PPT
10 strategy pattern
Abhijit Gaikwad
?
PPT
9 abstract interface
Abhijit Gaikwad
?
PPT
8 polymorphism
Abhijit Gaikwad
?
PPT
7 inheritance
Abhijit Gaikwad
?
Java concurrency
Abhijit Gaikwad
?
20 ch22 collections
Abhijit Gaikwad
?
17 sessions
Abhijit Gaikwad
?
16 cookies
Abhijit Gaikwad
?
15 decorator pattern
Abhijit Gaikwad
?
12 memory hierarchy
Abhijit Gaikwad
?
12 cache questions
Abhijit Gaikwad
?
10 strategy pattern
Abhijit Gaikwad
?
9 abstract interface
Abhijit Gaikwad
?
8 polymorphism
Abhijit Gaikwad
?
7 inheritance
Abhijit Gaikwad
?

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 ¨C the position of key in the array if matched or ¨C -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 snow?ake (demo) ? Sierpinski triangle (demo) 12