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.

Example 4.2: We demonstrate below some <strong>in</strong>terest<strong>in</strong>g applications of the<br />

logarithm rules from Proposition 4.1 (us<strong>in</strong>g the usual convention that the base of a<br />

logarithm is 2 if it is omitted).<br />

• log(2n) = log2 + log n = 1 + logn, by rule 1<br />

• log(n/2) = logn − log2 = logn − 1, by rule 2<br />

• logn 3 = 3logn, by rule 3<br />

• log2 n = nlog2 =n · 1 = n, by rule 3<br />

• log 4 n = (log n)/ log4 = (logn) /2, by rule 4<br />

• 2 logn = n log2 = n 1 = n, by rule 5.<br />

As a practical matter, we note that rule 4 gives us a way to compute the base-two<br />

logarithm on a calculator that has a base-10 logarithm button, LOG, for<br />

log 2 n = LOGn/LOG2.<br />

4.1.3 The L<strong>in</strong>ear function<br />

Another simple yet important function is the l<strong>in</strong>ear function,<br />

f(n)= n.<br />

That is, given an <strong>in</strong>put value n, the l<strong>in</strong>ear function f assigns the value n itself.<br />

This function arises <strong>in</strong> algorithm analysis any time we have to do a s<strong>in</strong>gle basic<br />

operation for each of n elements. For example, compar<strong>in</strong>g a number x to each<br />

element of an array of size n will require n comparisons. The l<strong>in</strong>ear function also<br />

represents the best runn<strong>in</strong>g time we can hope to achieve for any algorithm that<br />

processes a collection of n objects that are not already <strong>in</strong> the computer's memory,<br />

s<strong>in</strong>ce read<strong>in</strong>g <strong>in</strong> the n objects itself requires n operations.<br />

4.1.4 The N-Log-N function<br />

The next function we discuss <strong>in</strong> this section is the n-log-n function,<br />

f(n) = nlogn,<br />

that is, the function that assigns to an <strong>in</strong>put n the value of n times the logarithm<br />

base-two of n. This function grows a little faster than the l<strong>in</strong>ear function <strong>and</strong> a lot<br />

slower than the quadratic function. Thus, as we will show on several occasions, if<br />

we can improve the runn<strong>in</strong>g time of solv<strong>in</strong>g some problem from quadratic to n-logn,<br />

we will have an algorithm that runs much faster <strong>in</strong> general.<br />

216

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

Saved successfully!

Ooh no, something went wrong!