17.01.2013 Views

Data Structures and Algorithm Analysis in C - SVS

Data Structures and Algorithm Analysis in C - SVS

Data Structures and Algorithm Analysis in C - SVS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Structures</strong>, <strong>Algorithm</strong> <strong>Analysis</strong>: CHAPTER 2: ALGORITHM ANALYSIS<br />

iteration. However, we can prove that after two iterations, the rema<strong>in</strong>der is at<br />

most half of its orig<strong>in</strong>al value. This would show that the number of iterations is<br />

at most 2 log n = O(log n) <strong>and</strong> establish the runn<strong>in</strong>g time. This proof is easy, so<br />

we <strong>in</strong>clude it here. It follows directly from the follow<strong>in</strong>g theorem.<br />

unsigned <strong>in</strong>t<br />

gcd( unsigned <strong>in</strong>t m, unsigned <strong>in</strong>t n )<br />

{<br />

unsigned <strong>in</strong>t rem;<br />

/*1*/ while( n > 0 )<br />

{<br />

/*2*/ rem = m % n;<br />

/*3*/ m = n;<br />

/*4*/ n = rem;<br />

}<br />

/*5*/ return( m );<br />

}<br />

Figure 2.10 Euclid's algorithm.<br />

THEOREM 2.1.<br />

If m > n, then mmod n < m/2.<br />

PROOF:<br />

There are two cases. If n m/2, then obviously, s<strong>in</strong>ce the rema<strong>in</strong>der is<br />

smaller than n, the theorem is true for this case. The other case is n > m/2. But<br />

then n goes <strong>in</strong>to m once with a rema<strong>in</strong>der m - n < m/2, prov<strong>in</strong>g the theorem.<br />

One might wonder if this is the best bound possible, s<strong>in</strong>ce 2 log n is about 20<br />

for our example, <strong>and</strong> only seven operations were performed. It turns out that the<br />

constant can be improved slightly, to roughly 1.44 log n, <strong>in</strong> the worst case<br />

(which is achievable if m <strong>and</strong> n are consecutive Fibonacci numbers). The averagecase<br />

performance of Euclid's algorithm requires pages <strong>and</strong> pages of highly<br />

sophisticated mathematical analysis, <strong>and</strong> it turns out that the average number of<br />

iterations is about .<br />

Exponentiation<br />

页码,21/30<br />

Our last example <strong>in</strong> this section deals with rais<strong>in</strong>g an <strong>in</strong>teger to a power (which<br />

is also an <strong>in</strong>teger). Numbers that result from exponentiation are generally quite<br />

mk:@MSITStore:K:\<strong>Data</strong>.<strong>Structures</strong>.<strong>and</strong>.<strong>Algorithm</strong>.<strong>Analysis</strong>.<strong>in</strong>.C.chm::/...<br />

2006-1-27

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

Saved successfully!

Ooh no, something went wrong!