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.

In Figure 12.5, we illustrate the execution of the KMP pattern match<strong>in</strong>g algorithm<br />

on the same <strong>in</strong>put str<strong>in</strong>gs as <strong>in</strong> Example 12.3. Note the use of the failure function<br />

to avoid redo<strong>in</strong>g one of the comparisons between a character of the pattern <strong>and</strong> a<br />

character of the text. Also note that the algorithm performs fewer overall<br />

comparisons than the brute-force algorithm run on the same str<strong>in</strong>gs (Figure 12.1).<br />

Performance<br />

Exclud<strong>in</strong>g the computation of the failure function, the runn<strong>in</strong>g time of the KMP<br />

algorithm is clearly proportional to the number of iterations of the while loop. For<br />

the sake of the analysis, let us def<strong>in</strong>e k = i − j. Intuitively, k is the total amount by<br />

which the pattern P has been shifted with respect to the text T. Note that<br />

throughout the execution of the algorithm, we have k ≤ n. One of the follow<strong>in</strong>g<br />

three cases occurs at each iteration of the loop.<br />

• If T[i] = P[j], then i <strong>in</strong>creases by 1, <strong>and</strong> k does not change, s<strong>in</strong>ce j also<br />

<strong>in</strong>creases by 1.<br />

• If T[i] ≠ P[j] <strong>and</strong> j > 0, then i does not change <strong>and</strong> k <strong>in</strong>creases by at least 1,<br />

s<strong>in</strong>ce <strong>in</strong> this case k changes from i − j to i − f(j − 1), which is an addition of j −<br />

f(j − 1), which is positive because f(j − 1) < j.<br />

• If T[i] ≠ P[j] <strong>and</strong> j = 0, then i <strong>in</strong>creases by 1 <strong>and</strong> k <strong>in</strong>creases by 1, s<strong>in</strong>ce j<br />

does not change.<br />

Thus, at each iteration of the loop, either i or k <strong>in</strong>creases by at least 1 (possibly<br />

both); hence, the total number of iterations of the while loop <strong>in</strong> the KMP pattern<br />

match<strong>in</strong>g algorithm is at most 2n. Achiev<strong>in</strong>g this bound, of course, assumes that<br />

we have already computed the failure function for P.<br />

759

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

Saved successfully!

Ooh no, something went wrong!