Computer Science 101

Data Abstraction

Gregory M. Kapfhammer


flickr photo by "Cowboy" Ben Alman shared under a Creative Commons (BY-NC-ND) license

Color Scheme

Key Concept

Corresponding Diagram

In-Class Discussion

In-Class Activity

Details in the Textbook

Recursion achieves repetition

Recursion

Method makes one or more calls to itself

Process stops when a base case is reached

Visualized with a call tree or a program stack

Data structure relies on smaller instances of itself

Any questions about the definitions?

Elegant (yet, sometimes confusing!) approach

An Example

Recursive factorial

Can you find the recursive call?

Can you find the base case?

How do these programs work?

Review recursive factorial in greater detail

Trace of a recursive method call

See Figure 5.1 for a great diagram!

How does the JVM's stack support recursion?

Binary search

File system traversal

"Natural" solution is recursive!

Disk usage calculation

Types of Recursion

Linear

Binary

Multiple

See Section 5.3 for more details

Recursion can "run amok"

Incorrect recursion leads to inefficient algorithms

Be careful about how many recursive calls you create!

Computing Fibonacci numbers

See Page 217 for an Example

Why is this recursion run amok?

Maximum Recursive Depth

Details vary depending on JVM implementation

Possible to store about 1000 simultaneous calls

What happens when you exceed the limit?

Be careful to avoid StackOverflow exceptions!

Any questions about recursion?