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

Create successful ePaper yourself

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

Performance<br />

The brute-force pattern match<strong>in</strong>g algorithm could not be simpler. It consists of<br />

two nested loops, with the outer loop <strong>in</strong>dex<strong>in</strong>g through all possible start<strong>in</strong>g<br />

<strong>in</strong>dices of the pattern <strong>in</strong> the text, <strong>and</strong> the <strong>in</strong>ner loop <strong>in</strong>dex<strong>in</strong>g through each<br />

character of the pattern, compar<strong>in</strong>g it to its potentially correspond<strong>in</strong>g character <strong>in</strong><br />

the text. Thus, the correctness of the brute-force pattern match<strong>in</strong>g algorithm<br />

follows immediately from this exhaustive search approach.<br />

The runn<strong>in</strong>g time of brute-force pattern match<strong>in</strong>g <strong>in</strong> the worst case is not good,<br />

however, because, for each c<strong>and</strong>idate <strong>in</strong>dex <strong>in</strong> T, we can perform up to m<br />

character comparisons to discover that P does not match T at the current <strong>in</strong>dex.<br />

Referr<strong>in</strong>g to Code Fragment 12.1, we see that the outer for loop is executed at<br />

most n − m+ 1 times, <strong>and</strong> the <strong>in</strong>ner loop is executed at most m times. Thus, the<br />

runn<strong>in</strong>g time of the brute-force method is O((n − m+ 1)m), which is simplified as<br />

O(nm). Note that when m = n/2, this algorithm has quadratic runn<strong>in</strong>g time O(n 2 ).<br />

Example 12.3: Suppose we are given the text str<strong>in</strong>g<br />

T = "abacaabaccabacabaabb"<br />

<strong>and</strong> the pattern str<strong>in</strong>g<br />

P= "abacab".<br />

In Figure 12.1 we illustrate the execution of the brute-force pattern match<strong>in</strong>g<br />

algorithm on T <strong>and</strong> P.<br />

Figure 12.1: Example run of the brute-force pattern<br />

match<strong>in</strong>g algorithm. The algorithm performs 27<br />

character comparisons, <strong>in</strong>dicated above with numerical<br />

labels.<br />

749

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

Saved successfully!

Ooh no, something went wrong!