Boyer-Moore Algorithm
Boyer-Moore Algorithm
Boyer-moore algorithm
A N P A N M A N -
P A N - - - - - -
- P A N - - - - -
- - P A N - - - -
- - - P A N - - -
- - - - P A N - -
- - - - - P A N -
Alignments of pattern PAN to text ANPANMAN,
from k=3 to k=8. A match occurs at k=5.
Description
Previous to the introduction of this algorithm, the usual way to search within text
was to examine each character of the text for the first character of the pattern.
Once that was found the subsequent characters of the text would be compared to the
characters of the pattern. If no match occurred then the text would again be
checked character by character in an effort to find a match. Thus almost every
character in the text needs to be examined.
The key insight in this algorithm is that if the end of the pattern is compared to
the text, then jumps along the text can be made rather than checking every
character of the text. The reason that this works is that in lining up the pattern
against the text, the last character of the pattern is compared to the character in
the text. If the characters do not match, there is no need to continue searching
backwards along the text. If the character in the text does not match any of the
characters in the pattern, then the next character in the text to check is located
m characters farther along the text, where m is the length of the pattern. If the
character in the text is in the pattern, then a partial shift of the pattern along
the text is done to line up along the matching character and the process is
repeated. Jumping along the text to make comparisons rather than checking every
character in the text decreases the number of comparisons that have to be made,
which is the key to the efficiency of the algorithm.
The shift rules are implemented as constant-time table lookups, using tables
generated during the preprocessing of P.