25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

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.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 46<br />

WHILE (j > 0) & (i 0) & (i 0 dem<strong>and</strong>s that i > N; hence Q(i) implies Q(N),<br />

signalling that no match exists. Of course we still have to convince ourselves that Q(i) <strong>and</strong> P(i, j) are indeed<br />

invariants of the two repetitions. They are trivially satisfied when repetition starts, since Q(M) <strong>and</strong> P(x, M)<br />

are always true.<br />

Consider the first branch. Simultaneously decrementing k <strong>and</strong> j does not affect Q(i), <strong>and</strong>, since s k-<br />

1 = p j-1 had been established, <strong>and</strong> P(i, j) holds prior to decrementing j, then P(i, j) holds after it as well.<br />

In the second branch, it is sufficient to show that the statement i := i + d s[i-1] never falsifies the invariant<br />

Q(i) because P(i, j) is satisfied automatically after the remaining assignments. Q(i) is satisfied after<br />

incrementing i provided that before the assignment Q(i+d s[i-1] ) is guaranteed. Since we know that Q(i)<br />

holds, it suffices to establish ~R(i+h) for h = 1 .. d s[i-1] -1. We now recall that d x is defined as the<br />

distance of the rightmost occurrence of x in the pattern from the end. This is formally expressed as<br />

Ak: M-d x ≤ k < M-1 : p k ≠ x<br />

Substituting s i-1 for x, we obtain<br />

Ak: M-d s[i-1] ≤ k < M-1 : s i-1 ≠ p k<br />

= Ah: 1 ≤ h ≤ d s[i-1] -1 : si-1 ≠ p M-1-h<br />

⇒ Ah: 1 ≤ h ≤ d s[i-1] -1 : ~R(i+h)<br />

The following program includes the presented, simplified Boyer-Moore strategy in a setting similar to<br />

that of the preceding KMP-search program.<br />

PROCEDURE Search (VAR s, p: ARRAY OF CHAR; M, N: INTEGER; VAR r: INTEGER);<br />

(* ADenS193_BM *)<br />

(*search for pattern p of length M in text s of length N*)<br />

(*if p is found, then r indicates the position in s, otherwise r = -1*)<br />

VAR i, j, k: INTEGER;<br />

d: ARRAY 128 OF INTEGER;<br />

BEGIN<br />

FOR i := 0 TO 127 DO d[i] := M END;<br />

FOR j := 0 TO M-2 DO d[ORD(p[j])] := M-j-1 END;<br />

i := M; j := M; k := i;<br />

WHILE (j > 0) & (i 0) & (i

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

Saved successfully!

Ooh no, something went wrong!