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.

We conclude this section by analyz<strong>in</strong>g two algorithms that solve the same<br />

problem but have rather different runn<strong>in</strong>g times. The problem we are <strong>in</strong>terested <strong>in</strong><br />

is the one of comput<strong>in</strong>g the so-called prefix averages of a sequence of numbers.<br />

Namely, given an array X stor<strong>in</strong>g n numbers, we want to compute an array A such<br />

that A[i] is the average of elements X[0],…, X[i], for i = 0,…, n − 1, that is,<br />

Comput<strong>in</strong>g prefix averages has many applications <strong>in</strong> economics <strong>and</strong> statistics. For<br />

example, given the year-by-year returns of a mutual fund, an <strong>in</strong>vestor will<br />

typically want to see the fund's average annual returns for the last year, the last<br />

three years, the last five years, <strong>and</strong> the last ten years. Likewise, given a stream of<br />

daily Web usage logs, a Web site manager may wish to track average usage trends<br />

over various time periods.<br />

A Quadratic-Time Algorithm<br />

Our first algorithm for the prefix averages problem, called prefixAverages1,<br />

is shown <strong>in</strong> Code Fragment 4.1. It computes every element of A separately,<br />

follow<strong>in</strong>g the def<strong>in</strong>ition.<br />

Code Fragment 4.1: Algorithm prefixAverages1.<br />

Let us analyze the prefixAverages1 algorithm.<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 />

240

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

Saved successfully!

Ooh no, something went wrong!