23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

problems, however, a recursive implementation can be significantly simpler <strong>and</strong><br />

easier to underst<strong>and</strong> than an iterative implementation. Such an example follows.<br />

Figure 3.21: A recursion trace for the call<br />

recursiveFactorial(4).<br />

Draw<strong>in</strong>g an English Ruler<br />

As a more complex example of the use of recursion, consider how to draw the<br />

mark<strong>in</strong>gs of a typical English ruler. A ruler is broken up <strong>in</strong>to 1-<strong>in</strong>ch <strong>in</strong>tervals, <strong>and</strong><br />

each <strong>in</strong>terval consists of a set of ticks placed at <strong>in</strong>tervals of 1/2 <strong>in</strong>ch, 1/4 <strong>in</strong>ch, <strong>and</strong><br />

so on. As the size of the <strong>in</strong>terval decreases by half, the tick length decreases by one.<br />

(See Figure 3.22.)<br />

Figure 3.22: Three sample outputs of the rulerdraw<strong>in</strong>g<br />

function: (a) a 2-<strong>in</strong>ch ruler with major tick<br />

length 4; (b) a 1-<strong>in</strong>ch ruler with major tick length 5; (c) a<br />

3-<strong>in</strong>ch ruler with major tick length 3.<br />

190

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!