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.

The analysis of the runn<strong>in</strong>g time of algorithm prefixAverages2 follows:<br />

• Initializ<strong>in</strong>g <strong>and</strong> return<strong>in</strong>g array A at the beg<strong>in</strong>n<strong>in</strong>g <strong>and</strong> end can be done<br />

with a constant number of primitive operations per element, <strong>and</strong> takes O(n)<br />

time.<br />

• Initializ<strong>in</strong>g variable s at the beg<strong>in</strong>n<strong>in</strong>g takes O(1) time.<br />

• There is a s<strong>in</strong>gle for loop, which is controlled by counter i. The body of<br />

the loop is executed n times, for i = 0,… ,n − 1. Thus, statements s = s + X[i]<br />

<strong>and</strong> A[i] = s/(i+ 1) are executed n times each. This implies that these two<br />

statements plus the <strong>in</strong>crement<strong>in</strong>g <strong>and</strong> test<strong>in</strong>g of counter i contribute a number of<br />

primitive operations proportional to n, that is, O(n) time.<br />

The runn<strong>in</strong>g time of algorithm prefixAverages2 is given by the sum of three<br />

terms. The first <strong>and</strong> the third term are O(n), <strong>and</strong> the second term is O(1). By a<br />

simple application of Proposition 4.9, the runn<strong>in</strong>g time of prefixAverages2<br />

is O(n), which is much better than the quadratic-time algorithm<br />

prefixAverages1.<br />

4.2.6 A Recursive Algorithm for Comput<strong>in</strong>g Powers<br />

As a more <strong>in</strong>terest<strong>in</strong>g example of algorithm analysis, let us consider the problem of<br />

rais<strong>in</strong>g a number x to an arbitrary nonnegative <strong>in</strong>teger, n. That is, we wish to<br />

compute the power function p(x,n), def<strong>in</strong>ed as p(x,n) = x n . This function has an<br />

immediate recursive def<strong>in</strong>ition based on l<strong>in</strong>ear recursion:<br />

242

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

Saved successfully!

Ooh no, something went wrong!