Recursive Thinking Chapter 8 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.

Slides:



Advertisements
Similar presentations
Chapter 5 introduces the often- used data structure of linked lists. This presentation shows how to implement the most common operations on linked lists.
Advertisements

CSC211 Data Structures Lecture 9 Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Chapter 12 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach to the.
Chapter 8 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences of a problem.
Container Classes A container class is a data type that is capable of holding a collection of items. In C++, container classes can be implemented as.
L l One of the tree applications in Chapter 9 is binary search trees. l l In Chapter 9, binary search trees are used to implement bags and sets. l l This.
 One of the tree applications in Chapter 10 is binary search trees.  In Chapter 10, binary search trees are used to implement bags and sets.  This presentation.
 Chapter 2 introduces Object Oriented Programming.  OOP is a relatively new approach to programming which supports the creation of new data types and.
 Chapter 11 has several programming projects, including a project that uses heaps.  This presentation shows you what a heap is, and demonstrates two.
CSC212 Data Structure - Section AB Lecture 20 Hashing Instructor: Edgardo Molina Department of Computer Science City College of New York.
 Chapter 7 introduces the stack data type.  Several example applications of stacks are given in that chapter.  This presentation shows another use called.
P Chapter 6 introduces the stack data type. p Several example applications of stacks are given in that chapter. p This presentation shows another use called.
  Chapter 12 presents several common algorithms for sorting an array of integers.   Two slow but simple algorithms are Selectionsort and Insertionsort.
P p Chapter 10 has several programming projects, including a project that uses heaps. p p This presentation shows you what a heap is, and demonstrates.
CSC212 Data Structure - Section FG Lecture 21 Quadratic Sorting Instructor: Zhigang Zhu Department of Computer Science City College of New York.
 Chapter 10 introduces trees.  This presentation illustrates the simplest kind of trees: Complete Binary Trees. Complete Binary Trees Data Structures.
CSC212 Data Structure - Section FG Lecture 9 Linked Lists Instructor: Zhigang Zhu Department of Computer Science City College of New York.
Copyright © 1999, Carnegie Mellon. All Rights Reserved. Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple.
L l Chapter 11 discusses several ways of storing information in an array, and later searching for the information. l l Hash tables are a common approach.
 An important topic: preconditions and postconditions.  They are a method of specifying what a function accomplishes. Preconditions and Postconditions.
L l Chapter 4 introduces the often- used linked list data structures l l This presentation shows how to implement the most common operations on linked.
 Chapter 9 introduces the technique of recursive programming.  As you have seen, recursive programming involves spotting smaller occurrences of a problem.
Copyright © 2003 Pearson Education, Inc. Slide 1.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
CSC212 Data Structure - Section FG Lecture 12 Stacks and Queues Instructor: Zhigang Zhu Department of Computer Science City College of New York.
 Chapter 8 introduces the queue data type.  Several example applications of queues are given in that chapter.  This presentation describes the queue.
P An important topic: preconditions and postconditions. p They are a method of specifying what a function accomplishes. Preconditions and Postconditions.
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
P An important topic: preconditions and postconditions. p They are a method of specifying what a function accomplishes. Illinois State University Department.
CSC211 Data Structures Lecture 20 Hashing Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
 An important topic: preconditions and postconditions.  They are a method of specifying what a method accomplishes. Preconditions and Postconditions.
Software Development p Data structure p A collection of data organized so that the data can be accessed using a set of specific techniques p Object-oriented.
CSC211 Data Structures Lecture 21 Quadratic Sorting Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
CSC211 Data Structures Lecture 13 Recursive Thinking Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
P p Chapter 10 introduces trees. p p This presentation illustrates the simplest kind of trees: Complete Binary Trees. Complete Binary Trees Data Structures.
Container Classes  A container class is a data type that is capable of holding a collection of items.  In C++, container classes can be implemented as.
CSC212 Data Structure - Section AB Lecture 13 Recursive Thinking Instructor: Edgardo Molina Department of Computer Science City College of New York.
Using a Stack Chapter 6 introduces the stack data type.
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
Lecture 11 Recursive Thinking CSC212 Data Structure
CSC212 Data Structure - Section AB
To understand recursion, you have to understand recursion!
Collection Classes A Collection class is a data type that is capable of holding a group of items. In Java, Collection classes can be implemented as a class,
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Using a Stack Chapter 6 introduces the stack data type.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Using a Stack Chapter 6 introduces the stack data type.
Quadratic Sorting Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and.
CSC212 Data Structure - Section AB
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Using a Stack Chapter 6 introduces the stack data type.
Binary Search Trees One of the tree applications in Chapter 9 is binary search trees. In Chapter 9, binary search trees are used to implement bags and.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Preconditions and Postconditions
Using a Stack Chapter 6 introduces the stack data type.
Hash Tables Chapter 12 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
CSC212 Data Structure - Section KL
Binary Search Trees One of the tree applications in Chapter 9 is binary search trees. In Chapter 9, binary search trees are used to implement bags and.
Using a Queue Chapter 8 introduces the queue data type.
Linked Lists in Action Chapter 5 introduces the often- used data structure of linked lists. This presentation shows how to implement the most common.
Using a Queue Chapter 8 introduces the queue data type.
Preconditions and Postconditions
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Complete Binary Trees Chapter 9 introduces trees.
Hash Tables Chapter 11 discusses several ways of storing information in an array, and later searching for the information. Hash tables are a common approach.
Presentation transcript:

Recursive Thinking Chapter 8 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences of a problem within the problem itself. This presentation gives an additional example, which is not in the book. This lecture demonstrates a typical pattern that arises in recursive methods. The lecture can be given shortly before or shortly after the students have read Section 8.1. By the way, the book delays the introduction of recursion until just before trees. Our reasoning here is that recursive methods with linked lists can sometimes be bad programming practice because the run-time stack must grow to the length of the linked list (and iterative algorithms are usually just as easy). On the other hand, the depth of recursive tree algorithms is merely the depth of the tree (and equivalent iterative algorithms can be harder to program). Data Structures and Other Objects Using Java

A Car Object To start the example, think about your favorite family car In this lecture, we're going to design a recursive method which manipulates a new object called a Car. In order to explain the Car that I have in mind, think about your favorite family car... NOTE: In Powerpoint, the next few slides will automatically appear every few seconds...

A Car Object To start the example, think about your favorite family car ...let's try for something a bit more modern that this...

A Car Object To start the example, think about your favorite family car ...no, that's too conservative...

A Car Object To start the example, think about your favorite family car ...that's better!

A Car Object To start the example, think about your favorite family car Imagine that the car is controlled by a radio signal from a computer I want you to imagine that this family car is being controlled by a radio signal coming from your computer.

A Car Class To start the example, think about your favorite family car Imagine that the car is controlled by a radio signal from a computer The radio signals are generated by activating methods of a Car object public class Car { . . . } The radio signals themselves are generated by writing a program which uses a new object type called a Car. Each time one of the car methods is activated, the computer sends a radio signal to control the car. This may seem a bit far-fetched, but such radio-controlled hardware really does exist, and the hardware is controlled by programs which could have objects such as these. A similar example is an automatic baggage system at an airport, which is controlled by a computer. Also, remember that in order to understand this example, you don't need to know all the details of how the Car's methods work. All you need to know is what each of the Car's methods accomplishes. I have four particular methods in mind, and I'll describe what each method does.

methods for the Car Class public class Car { public Car(int carNumber); public public void move( ); public void turnAround( ); public boolean isBlocked( ); ... We don't need to know the private fields! ... } Here are the prototypes of the four methods. Let's look at each method in turn...

The Constructor When we declare a Car and activate the constructor, the computer makes a radio link with a car that has a particular number. public static void main(...) { Car racer = new Car(7); . . . This example demonstrates the usage of the constructor. In this example, we have declared a Car called racer and the activated the constructor with the argument 7. The argument 7 just indicates which of several cars we want to control. Each car needs to have a unique number. In this example, we are making a radio connection to "Car Number 7". Any future radio signals generated by activating racer's methods will control "Car Number 7".

The turnAround method When we activate turnAround, the computer signals the car to turn 180 degrees. public static void main(...) { Car racer = new Car(7); racer.turnAround( ); . . . After the connection is made, we can activate other methods of racer. In this example, we are activating racer.turnAround( ); The method sends a radio signal to the car, telling it to turn 180 degrees. (In case you hadn't noticed, the car has a very small turning radius!)

The move method When we activate move, the computer signals the car to move forward one foot. public static void main(...) { Car racer = new Car(7); racer.turnAround( ); racer.move( ); . . . Here's an example of the third Car method in action. When we activate racer.move( ); the result is a radio signal which tells the car to move forward one foot. NOTE: In Powerpoint, the next slide automatically appears, moving the car forward "one foot".

The move method When we activate move, the computer signals the car to move forward one foot. public static void main(...) { Car racer = new Car(7); racer.turnAround( ); racer.move( ); . . . As you can see, the car has moved forward by a foot.

The isBlocked( ) method The isBlocked method detects barriers. public static void main(...) { Car racer = new Car(7); racer.turnAround( ); racer.move( ); if (racer.isBlocked( ) ) System.out.println (“Cannot move!”); . . . The last Car method is a public booleanean method called isBlocked. The method returns true if there is some barrier in front of the car, making it impossible to move. The method returns false if the front of the car is unblocked, making a move possible. A question: What will racer.isBlocked return in this example? Answer: True, because there is a definite barrier in front of the car. Another question: Can you state a good precondition for the move method? Answer: isBlocked must return false.

Your Mission Write a method which will move a Car forward until it reaches a barrier... Now we can examine the problem that I have in mind. I want to write a method which will move a Car forward until it reaches a barrier...

Your Mission Write a method which will move a Car forward until it reaches a barrier... ...as shown here. NOTE: In Powerpoint, this slide automatically appears after six seconds. Each of the next few slides automatically appears after a few more seconds.

Your Mission Write a method which will move a Car forward until it reaches a barrier... Here, you can see that the barrier has been reached. But that is not the end of the method’s work. The method must next...

Your Mission Write a method which will move a Car forward until it reaches a barrier... ...then the car is turned around... ...turn the car around...

Your Mission Write a method which will move a Car forward until it reaches a barrier... ...then the car is turned around... ...and returned to its original location, facing the opposite way. ...and move the car back to its original position, facing the opposite direction.

Your Mission Write a method which will move a Car forward until it reaches a barrier... ...then the car is turned around... ...and returned to its original location, facing the opposite way. This is the end of the method’s work.

Your Mission public void ricochet(Car movingCar) Write a method which will move a Car forward until it reaches a barrier... ...then the car is turned around... ...and returned to its original location, facing the opposite way. The method, called ricochet, has the heading shown here. There is one parameter, called movingCar, which is the Car that the method manipulates. We will assume that the radio connection has already been made for this car, so all the method has to do is issue the necessary move and turnAround commands.

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. The first action the method takes is to check for a very simple case: the case where the car is already blocked. In this case, no movement is needed. All that the method needs to do is turn the car around, and leave it in the same place. NOTE: The lecturer can pretend to be the car, blocked at a wall, to demonstrate this simple case.

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: On the other hand, if the car is not blocked, then some movement is needed. The method begins the movement by moving the car forward just one foot. Notice that the move activation is not in a loop. We're just moving one foot, with the primary goal being to make a smaller version of the original problem. In fact, once the car has moved just a single foot forward, we do have a smaller version of the original problem... movingCar.move( ); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); This makes the problem a bit smaller. For example, if the car started 100 feet from the barrier... if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...as shown in this example. In this example, the car starts 100 feet from a barrier. movingCar.move( ); . . . 100 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); This makes the problem a bit smaller. For example, if the car started 100 feet from the barrier... then after activating move once, the distance is only 99 feet. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: After moving just one foot, the car is 99 feet from the barrier. movingCar.move( ); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); We now have a smaller version of the same problem that we started with. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: Since 99 feet is less than 100 feet, we have a smaller version of the original problem. movingCar.move( ); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); Make a recursive call to solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: Once a smaller problem has been created, we can make the key step of any recursive method: The ricochet method calls itself to solve the smaller problem! The act of a method calling itself is recursion, or in other words a recursive call. In order for recursion to succeed, the recursive call must be asked to solve a problem which is somehow smaller than the original problem. The precise meaning of "smaller" is given in Section 8.3, but for now you can use your intuition about what a "smaller" problem is. movingCar.move( ); ricochet(movingCar); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: The key idea to remember is this: When you make a recursive call to solve a smaller problem, the recursive call will successfully solve that smaller problem. In this case, that means that the recursive call will move the car 99 feet to the barrier... movingCar.move( ); ricochet(movingCar); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...as shown here and in the next few slides. movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: This is still work being done in the recursive call. movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: Still in that recursive call! movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: The work of the recursive call has taken the car to the barrier... movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...and turned the car around. movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: The recursive call is still working to solve the smaller problem... movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...eventually the recursive call will bring the car back... movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...to the position where the recursive call was made. movingCar.move( ); ricochet(movingCar); . . .

Pseudocode for ricochet public void ricochet(Car movingCar); The recursive call will solve the smaller problem. if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: At last! The recursive call has finished its work, solving the smaller problem. In the solution of the smaller problem, the recursive call moved the car forward to the barrier, turned the car around, and moved the car back to the starting position of the smaller problem, but facing the opposite direction Another key point: You don't need to know all the details of how that recursive call worked. Just have confidence that the recursive call will solve the smaller problem. You can safely have this confidence provided that: 1. When the problem gets small enough, there won't be more recursive calls, and 2. Each recursive call makes the problem "smaller". movingCar.move( ); ricochet(movingCar); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); What is the last step that's needed to return to our original location ? if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: After the recursive call solves the smaller problem, there is one more step that must be taken to solve the original problem. Question: What is that remaining step? movingCar.move( ); ricochet(movingCar); . . . 99 ft.

Pseudocode for ricochet public void ricochet(Car movingCar); What is the last step that's needed to return to our original location ? if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: Answer: The car must be moved one more step to bring it back to its original position. movingCar.move( ); ricochet(movingCar); 100 ft.

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: This recursive method follows a common pattern that you should recognize. The pattern followed by this recursive method is a common one that you should be able to recognize and implement for similar problems. movingCar.move( ); ricochet(movingCar);

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: When the problem is simple, solve it with no recursive call. This is the base case. The start of the pattern is called the base case. This is the case where the problem is so simple that it can be solved with no recursion. Question: What do you suppose would happen if we forgot to include a base case? Answer: In theory, the recursion would never end. Each recursive call would make another recursive call which would make another recursive call, and so on forever. In practice, each recursive call uses some of the computer's memory, and eventually you will run out of memory. At that point, a run-time error occurs stating "Run-time stack overflow" or perhaps "Stack-Heap collision." Both messages mean that you have run out of memory to make method calls. movingCar.move( ); ricochet(movingCar);

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: When the problem is more complex, start by doing work to create a smaller version of the same problem... If the base case does not apply, then the algorithm will work by creating a smaller version of the original problem. movingCar.move( ); ricochet(movingCar);

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...use a recursive call to completely solve the smaller problem... The smaller problem is solved with a recursive call. movingCar.move( ); ricochet(movingCar);

Pseudocode for ricochet public void ricochet(Car movingCar) if movingCar.isBlocked( ), then the car is already at the barrier. In this case, just turn the car around. Otherwise, the car has not yet reached the barrier, so start with: ...and finally do any work that's needed to complete the solution of the original problem.. Generally a bit of extra work is done before the recursive call, in order to create the smaller problem. Work is often needed after the recursive call too, to finish solving the larger problem. Programmer's Hint: If you find that no work is needed after the recursive call, then you have a simple kind of recursion called "tail recursion". The word "tail" refers to the fact that the recursive call is the final thing the algorithm does. Tail recursion is nearly always a bad idea. The reason is that tail recursive algorithms can generally be written much simpler with a loop and no recursive call. movingCar.move( ); ricochet(movingCar);

Implementation of ricochet public void ricochet(Car movingCar) { if (movingCar.isBlocked( )) movingCar.turnAround( ); // Base case else { // Recursive pattern movingCar.move( ); ricochet(movingCar); } Look for this pattern in the other examples of Chapter 8. You'll find this same pattern in other problems of Chapter 9, such as the recursive methods to write the digits of a number vertically.

An Exercise Can you write ricochet as a new method of the Car class, instead of a separate method? public void ricochet( ) { . . . Time for another quiz . . . You have 2 minutes to write the implementation.

An Exercise One solution: public void ricochet( ) { if (isBlocked( )) turnAround( ); // Base case else { // Recursive pattern move( ); ricochet( ); } Two key points: 1. The recursive method does not need a parameter, since it must be activated by a particular car. For example, if you have a car named racer, then you can activate racer's ricochet method with: racer.ricochet( ); 2. The recursive method activates itself. Do you see where this happens?

THE END Presentation copyright 1999 Addison Wesley Longman, For use with Data Structures and Other Objects Using Java by Michael Main. Some artwork in the presentation is used with permission from Presentation Task Force (copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyright Corel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image Club Graphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc). Students and instructors who use Data Structures and Other Objects Using Java are welcome to use this presentation however they see fit, so long as this copyright notice remains intact. Feel free to send your ideas to: Michael Main main@colorado.edu THE END