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.

This def<strong>in</strong>ition leads immediately to a recursive algorithm that uses O(n) method<br />

calls to compute p(x,n). We can compute the power function much faster than this,<br />

however, by us<strong>in</strong>g the follow<strong>in</strong>g alternative def<strong>in</strong>ition, also based on l<strong>in</strong>ear<br />

recursion, which employs a squar<strong>in</strong>g technique:<br />

To illustrate how this def<strong>in</strong>ition works, consider the follow<strong>in</strong>g examples:<br />

2 4 = 2 (4/2)2 = (2 4/2 ) 2 = (2 2 ) 2 = 4 2 = 16<br />

2 5 = 2 1 + (4/2)2 = 2(2 4/2 ) 2 = 2(2 2 ) 2 = 2(4 2 ) = 32<br />

2 6 = 2 (6/2)2 = (2 6/2 ) 2 = (2 3 ) 2 = 8 2 = 64<br />

2 7 = 2 1 + (6/2)2 = 2(2 6/2 ) 2 = 2(2 3 ) 2 = 2(8 2 ) = 128.<br />

This def<strong>in</strong>ition suggests the algorithm of Code Fragment 4.3.<br />

Code Fragment 4.3: Comput<strong>in</strong>g the power function<br />

us<strong>in</strong>g l<strong>in</strong>ear recursion.<br />

To analyze the runn<strong>in</strong>g time of the algorithm, we observe that each recursive call of<br />

method Power(x, n) divides the exponent, n, by two. Thus, there are O(logn)<br />

recursive calls, not O(n). That is, by us<strong>in</strong>g l<strong>in</strong>ear recursion <strong>and</strong> the squar<strong>in</strong>g<br />

243

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

Saved successfully!

Ooh no, something went wrong!