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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Analyz<strong>in</strong>g Recursive <strong>Algorithms</strong> us<strong>in</strong>g Recursion Traces<br />

We can analyze a recursive algorithm by us<strong>in</strong>g a visual tool known as a recursion<br />

trace. We used recursion traces, for example, to analyze <strong>and</strong> visualize the<br />

recursive Fibonacci function of Section 3.5, <strong>and</strong> we will similarly use recursion<br />

traces for the recursive sort<strong>in</strong>g algorithms of Sections 11.1 <strong>and</strong> 11.2.<br />

To draw a recursion trace, we create a box for each <strong>in</strong>stance of the method <strong>and</strong><br />

label it with the parameters of the method. Also, we visualize a recursive call by<br />

draw<strong>in</strong>g an arrow from the box of the call<strong>in</strong>g method to the box of the called<br />

method. For example, we illustrate the recursion trace of the L<strong>in</strong>earSum<br />

algorithm of Code Fragment 3.31 <strong>in</strong> Figure 3.24. We label each box <strong>in</strong> this trace<br />

with the parameters used to make this call. Each time we make a recursive call,<br />

we draw a l<strong>in</strong>e to the box represent<strong>in</strong>g the recursive call. We can also use this<br />

diagram to visualize stepp<strong>in</strong>g through the algorithm, s<strong>in</strong>ce it proceeds by go<strong>in</strong>g<br />

from the call for n to the call for n − 1, to the call for n − 2, <strong>and</strong> so on, all the way<br />

down to the call for 1. When the f<strong>in</strong>al call f<strong>in</strong>ishes, it returns its value back to the<br />

call for 2, which adds <strong>in</strong> its value, <strong>and</strong> returns this partial sum to the call for 3, <strong>and</strong><br />

so on, until the call for n − 1 returns its partial sum to the call for n.<br />

Figure 3.24: Recursion trace for an execution of<br />

L<strong>in</strong>earSum(A,n) with <strong>in</strong>put parameters A = {4,3,6,2,5}<br />

<strong>and</strong> n = 5.<br />

From Figure 3.24, it should be clear that for an <strong>in</strong>put array of size n, Algorithm<br />

L<strong>in</strong>earSum makes n calls. Hence, it will take an amount of time that is roughly<br />

proportional to n, s<strong>in</strong>ce it spends a constant amount of time perform<strong>in</strong>g the<br />

196

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

Saved successfully!

Ooh no, something went wrong!