Skip to content

Boyer-Moore-Horspool

words

Level 2 of 3

Also called Horspool's algorithm and Boyer-Moore-Horspool algorithm.

how it works

The idea on the watch page's first example, paste in toothpaste. Then the whole method on it, step by step. A position is a letter's number in the text, from 1; in the watch page's table, * means any other letter.

Look for paste in toothpaste. First write a table from the pattern alone. For each letter but its last, how far it stands from the end: p 4, a 3, s 2, t 1. Any other letter jumps 5, the whole pattern. A letter found twice before the last keeps the copy nearer the end, the smaller jump: in bbb, b jumps 1, not 2. Put paste under the text's start and compare from its last letter back. The text's h is not e: 1 comparison. Look up h, the text's letter above the pattern's last. The jump slides the pattern right until its nearest copy of that letter lies under the text's letter; a smaller slide puts a different letter there, which cannot match. h is not in the table, so the pattern jumps 5, past h. At place 6, e, t, s, a and p all match, so paste stands at place 6: 5 comparisons. e stands only last in paste, so it is not in the table: it jumps 5, past the end. 2 places cost 1 + 5, which is 6 comparisons; brute force tries all 6 places and makes 10. The code below counts places from 0 and returns them in a list, so it returns [5].

letterpastany other
jump43215
The table for paste. Each letter but the last jumps by how far it stands from the end; any other letter, 5.
123456
intent
ten
ten
ten in intent. At place 1, t lies above the pattern's last letter; ten's nearest t is 2 from its end, so it jumps 2 and puts its t under that t. A jump of 1 would put e there, which cannot match.
placeletters abovecompared from the endcomparisonsjump
1toothh is not e1h: 5
6pasteall 5 match5, a matche: 5
all6
paste tried at 2 places of toothpaste. Places 2 to 5 are jumped over.
Paste in toothpaste: 6 moments of its 17 steps, the steps between them left for the watch page
  1. step 1 of 17

    toothpastepastepast*

    Look for paste in toothpaste. First write a table, from the pattern alone, of how far it may jump.

    what it remembers to know where it is
    pattern stands at place
    1
    text letter under its last letter
    not yet
    jump allowed
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 6 of 17

    toothpastepastepast*43215

    Any other letter is nowhere in the pattern before its last letter, so with it under the pattern's last letter the pattern may jump its whole length, 5.

    what it remembers to know where it is
    pattern stands at place
    1
    text letter under its last letter
    not yet
    jump allowed
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  3. step 7 of 17

    toothpastepastepast*43215

    The text's h at position 5 is not the pattern's e, so the pattern does not stand here.

    what it remembers to know where it is
    pattern stands at place
    1
    text letter under its last letter
    not yet
    jump allowed
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 9 of 17

    toothpastepastepast*43215

    Jump the pattern on 5 places, to place 6, and compare from its last letter again.

    what it remembers to know where it is
    pattern stands at place
    6
    text letter under its last letter
    h
    jump allowed
    5

    watch from here

  5. step 15 of 17

    toothpastepastepast*43215

    Every letter matched: the pattern stands at place 6. Mark it.

    what it remembers to know where it is
    pattern stands at place
    6
    text letter under its last letter
    h
    jump allowed
    5

    watch from here

  6. step 17 of 17

    toothpastepastepast*43215

    The pattern would run past the end of the text. It stands at 1 place. That took 6 comparisons.

    what it remembers to know where it is
    pattern stands at place
    6
    text letter under its last letter
    e
    jump allowed
    5

    watch from here

the steps, in plain words
  1. for each letter of the pattern but its last, write how far it stands from the end; any other letter, the whole lengthPython lines 8, 9 and 10
  2. while the pattern fits under the text, compare it with the text from its last letter back, until one differsPython lines 13, 14, 16 and 17
  3. if every letter matched, mark a matchPython lines 18 and 19
  4. look up the text letter under the pattern's last letter, and jump the pattern on that farPython line 21
  5. the pattern would run past the end of the text, so every match is foundPython line 22
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def boyer_moore_horspool(text, pattern):
    """Find every place a pattern stands in a text, jumping ahead by a table.

    text and pattern are each a run of letters, the pattern no longer than
    the text. Returns the places it stands, counted from 0.
    """
    n, m = len(text), len(pattern)
    jump = {}  # each letter's jump, kept by its number, ord(letter)
    for i in range(m - 1):  # each letter of the pattern but its last
        jump[ord(pattern[i])] = m - 1 - i  # how far it stands from the end
    places = []
    place = 0
    while place + m <= n:  # while the pattern fits under the text
        j = m - 1
        # compare from the pattern's last letter back, until one differs
        while j >= 0 and text[place + j] == pattern[j]:
            j -= 1
        if j < 0:  # every letter matched
            places.append(place)  # so it stands here
        # jump by the text's letter above the pattern's last; any other, m
        place += jump.get(ord(text[place + m - 1]), m)
    return places  # the pattern would run past the end: every match found

how it scales

The plot counts the comparisons on a text of nn letters and a pattern half as long, rounded up, in two ways. The best shares no letter with the text and jumps the whole pattern. The worst matches at every place and jumps 1. Measured from 10 to 10,000.

Each mark across or up is ten times the one before. The best line lies flat: 2 comparisons at every size measured, as each is even; an odd size costs 1. The worst climbs two marks up for each mark across: 2,550 at 100, 250,500 at 1,000. Ten times the letters, about 100 times the comparisons. Section 4 derives both.

letters compared, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, how many letters the text has, ten times more at each mark to the right

  • a text of a's and a pattern of a's, half as longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a text of a's and a pattern of b's, half as longsolid where measured by running it; dashed where its formula carries it on to ten million
how long the worst takes, at a billion comparisons a second
nnletters comparedtime
1,000250,500about 251 microseconds
100,0002,500,050,000about 2.5 seconds
10,000,00025,000,005,000,000about 6.9 hours

The letters compared are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Boyer-Moore-Horspool's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it makes a text of n
letters a and a pattern of half as many letters, rounded up, in two ways:
all b, so the last letter differs at once and a jumps the whole pattern,
the fewest; and all a, so every letter matches at every place and a jumps
1, the most. It prints the comparisons for each, by count
below, which counts each letter of the text compared with a letter of the
pattern. The counts are the same on any computer; only the time differs.
"""


def boyer_moore_horspool(text, pattern):
    """Find every place a pattern stands in a text, jumping ahead by a table.

    text and pattern are each a run of letters, the pattern no longer than
    the text. Returns the places it stands, counted from 0.
    """
    n, m = len(text), len(pattern)
    jump = {}  # each letter's jump, kept by its number, ord(letter)
    for i in range(m - 1):  # each letter of the pattern but its last
        jump[ord(pattern[i])] = m - 1 - i  # how far it stands from the end
    places = []
    place = 0
    while place + m <= n:  # while the pattern fits under the text
        j = m - 1
        # compare from the pattern's last letter back, until one differs
        while j >= 0 and text[place + j] == pattern[j]:
            j -= 1
        if j < 0:  # every letter matched
            places.append(place)  # so it stands here
        # jump by the text's letter above the pattern's last; any other, m
        place += jump.get(ord(text[place + m - 1]), m)
    return places  # the pattern would run past the end: every match found


def count(text, pattern):
    """How many comparisons boyer_moore_horspool makes: one for each letter
    of the text it compares with a letter of the pattern."""
    n, m = len(text), len(pattern)
    jump = {}
    for i in range(m - 1):
        jump[ord(pattern[i])] = m - 1 - i
    compared = 0
    place = 0
    while place + m <= n:
        j = m - 1
        while j >= 0:
            compared += 1
            if text[place + j] != pattern[j]:
                break
            j -= 1
        place += jump.get(ord(text[place + m - 1]), m)
    return compared


def cheapest(n):
    """A text of n a's and a pattern of half as many b's, rounded up."""
    return "a" * n, "b" * ((n + 1) // 2)


def dearest(n):
    """A text of n a's and a pattern of half as many a's, rounded up."""
    return "a" * n, "a" * ((n + 1) // 2)


if __name__ == "__main__":
    print(f"{'n':>7} {'all b':>8} {'all a':>12}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000):
        print(f"{n:>7} {count(*cheapest(n)):>8} {count(*dearest(n)):>12}")

best, worst and average

Here best and worst are texts and patterns of the same lengths, nn letters and ⌈n2⌉\lceil \frac{n}{2} \rceil, half of nn rounded up, as on brute force's page. The letters set the jumps: the best jumps the whole pattern, the worst 1. For 6 letters and 3, the best makes 2 comparisons and the worst 12. No average is worked out.

A case is one kind of text and pattern. A bound says how fast its cost grows as letters are added.

The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. At 10,000 letters the worst is 5,000 times 5,001: 5,000 times 5,000, which is 25,000,000, plus 5,000. They are the pieces n24\frac{n^2}{4} and half of nn, and the first is nearly all of it. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta text of a's and a pattern of b's, half as longworsta text of a's and a pattern of a's, half as long
letters compared⌊n2⌋−⌈n2⌉+2\lfloor \frac{n}{2} \rfloor - \lceil \frac{n}{2} \rceil + 2⌈n2⌉(⌊n2⌋+1)\lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1)
how the letters compared grow in each case
tight, Θ\ThetaΘ(1)\Theta(1)Θ(n2)\Theta(n^2)
ceiling, OOO(1)O(1)O(n2)O(n^2)
floor, Ω\OmegaΩ(1)\Omega(1)Ω(n2)\Omega(n^2)

extra memory: a jump for each different letter before the pattern's last, and the place, beside the places found

Extra memory is the room it needs on top of the input itself, while it runs.

textpatternplaces triedcomparisons
toothpastepaste26
bananaana37
everythingzoo33
aaaaaaaaaabaaaa630
The watch page's four examples. everything has no z or o, so each place costs 1 and jumps 3. The 10 a's cost 5 at every place.
nbestworst
6212
7116
10230
The two cases, a pattern half the text, rounded up. At 10 letters the worst costs 30, as the watch page's last example does.
patternplaces triedcomparisons
a66
aa510
aaa412
aaaa312
aaaaa210
aaaaaa16
A text of 6 a's and a pattern of a's of each length. 3 and 4 letters cost the most.

where the formula comes from

Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 keeps the pattern at 5 letters as the text grows, so every jump moves it 5 places.

Question 1: how many comparisons, FF, on a text of nn a's and a pattern of mm b's, mm half of nn rounded up?
  1. the move: the jump for a

    the line:
    a is not in the pattern:it jumps m\begin{gathered} \text{a is not in the pattern:} \\ \text{it jumps } m \end{gathered}
    letterbany other
    jump13
    The table for bbb. Of the two b's before the last, the nearer stands 1 from the end; any other letter jumps the whole pattern, 3.

    why it is allowed: The pattern is all b. At every place the text's letter above the pattern's last is an a. a is not in the table, so the pattern jumps its whole length, mm.

  2. the move: one comparison a place

    the line:
    each place tried:1 comparison\begin{gathered} \text{each place tried:} \\ 1 \text{ comparison} \end{gathered}

    why it is allowed: The pattern's last letter, b, is compared first, with an a, and differs. So each place tried costs 1.

  3. the move: the last place

    the line:
    the last place:n−m+1\begin{gathered} \text{the last place:} \\ n - m + 1 \end{gathered}
    123456
    aaaaaa
    bbb
    Positions 1 to 6, the text above and the pattern at its last place below. Its 3 letters end under letter 6, so they start under 6 - 3 + 1, which is 4.

    why it is allowed: At its last place, the pattern's last letter is under the text's last, nn, and its mm letters cover letters n−m+1n - m + 1 to nn. For 6 letters and 3, place 4.

  4. the move: the second place

    the line:
    place 1+m is tried exactlywhen it is at most n−m+1\begin{gathered} \text{place } 1 + m \text{ is tried exactly} \\ \text{when it is at most } n - m + 1 \end{gathered}
    nmlast placesecond placeplaces tried
    63441 and 4
    74451
    84551 and 5
    A text of a's, a pattern of b's half as long. Place 1 + m is tried exactly when it is at most the last place.

    why it is allowed: By line 1, a jump of mm from place 1 lands on place 1+m1 + m, which must not pass line 3's last place. For 6 letters and 3, place 4 is tried; for 7 and 4, place 5 passes place 4.

  5. the move: the pattern half the text

    the line:
    m is ⌈n2⌉,n−m is ⌊n2⌋\begin{gathered} m \text{ is } \lceil \frac{n}{2} \rceil, \\ n - m \text{ is } \lfloor \frac{n}{2} \rfloor \end{gathered}

    why it is allowed: The cases take a pattern half the text, rounded up, as its mm. Half of nn rounded up and half of nn rounded down add up to nn, so n−mn - m is the half rounded down. For 6, 3 and 3; for 7, 4 and 3.

  6. the move: take 1 from both sides

    the line:
    place 1+m is tried exactly whenm is at most n−m\begin{gathered} \text{place } 1 + m \text{ is tried exactly when} \\ m \text{ is at most } n - m \end{gathered}

    why it is allowed: Line 4, with 1 taken from both sides. For 6 letters and 3, 3 is at most 3.

  7. the move: put in line 5

    the line:
    tried exactly when ⌈n2⌉is at most ⌊n2⌋\begin{gathered} \text{tried exactly when } \lceil \frac{n}{2} \rceil \\ \text{is at most } \lfloor \frac{n}{2} \rfloor \end{gathered}

    why it is allowed: Line 6, with line 5's halves put in for mm and n−mn - m. For 7, 4 is more than 3.

  8. the move: the halves equal

    the line:
    tried exactly when the twohalves are equal: an even n\begin{gathered} \text{tried exactly when the two} \\ \text{halves are equal: an even } n \end{gathered}

    why it is allowed: Rounding up never gives less than rounding down, so at most means equal, which happens only when n2\frac{n}{2} is whole. For 6, 3 and 3.

  9. the move: no third place

    the line:
    place 1+2m is past the end\text{place } 1 + 2m \text{ is past the end}

    why it is allowed: Two jumps of mm, by line 1. By line 5, 2m2m is at least nn, so place 1+2m1 + 2m starts past letter nn.

  10. the move: one place or two

    the line:
    F=⌊n2⌋−⌈n2⌉+2F = \lfloor \frac{n}{2} \rfloor - \lceil \frac{n}{2} \rceil + 2
    nhalf downhalf upplacesF
    63322
    73411
    For 6, 3 - 3 + 2 is 2; for 7, 3 - 4 + 2 is 1.

    why it is allowed: By lines 8 and 9, 2 places for an even nn, where ⌊n2⌋−⌈n2⌉\lfloor \frac{n}{2} \rfloor - \lceil \frac{n}{2} \rceil is 0, and 1 for an odd one, where it is -1. 1 comparison each by line 2. For 6, 2; for 7, 1.

  11. the move: no search costs less

    the line:
    no text and pattern ofthese lengths cost less\begin{gathered} \text{no text and pattern of} \\ \text{these lengths cost less} \end{gathered}

    why it is allowed: Every search compares at place 1, at least 1. No jump is more than mm, the whole pattern. So for an even nn the first jump lands at most on place 1+m1 + m, the last by lines 3 and 5. So a second place is always tried, at least 2. For 6, 2.

  12. the move: a ceiling

    the line:
    F≤2F \le 2

    why it is allowed: Half of nn rounded down is never more than half rounded up, so line 10 is at most 0 + 2. For 6, 2.

  13. the move: read the bound

    the line:
    F∈O(1)F \in O(1)

    why it is allowed: By line 12, with the fixed multiple 2: at most 2 times 1, however long the text.

  14. the move: a floor

    the line:
    F≥1F \ge 1

    why it is allowed: Half of nn rounded up is at most 1 more than half rounded down, so line 10 is at least -1 + 2. For 7, 1.

  15. the move: read the bound

    the line:
    F∈Ω(1)F \in \Omega(1)

    why it is allowed: By line 14, with the fixed multiple 1.

  16. the move: both together

    the line:
    F∈Θ(1)F \in \Theta(1)

    why it is allowed: Lines 13 and 15, a ceiling and a floor of the same growth: a fixed number, however long the text.

try it with a small nn: at n=6n = 6, line 10 gives F=2F = 2, which you can work out by hand

Question 2: how many comparisons, MM, on a text of nn a's and a pattern of mm a's, mm half of nn rounded up?
  1. the move: a place's most

    the line:
    a place comparesat most m letters\begin{gathered} \text{a place compares} \\ \text{at most } m \text{ letters} \end{gathered}

    why it is allowed: At a place the pattern's letters are compared from its last back, one each, until one differs. It has mm letters, so at most mm.

  2. the move: every letter matches

    the line:
    all a’s:m at every place\begin{gathered} \text{all a's:} \\ m \text{ at every place} \end{gathered}
    placetextpatterncomparisons
    1aaaaaa3, a match
    2aaaaaa3, a match
    3aaaaaa3, a match
    4aaaaaa3, a match
    all12
    A text of 6 a's and the pattern aaa. At each of the 4 places all 3 letters match. 4 times 3 is 12.

    why it is allowed: The text and the pattern are all a, so every letter matches from the end back: line 1's most, mm, at every place tried, each a match.

  3. the move: a jumps 1

    the line:
    a jumps 1:every place is tried\begin{gathered} \text{a jumps 1:} \\ \text{every place is tried} \end{gathered}
    letteraany other
    jump13
    The table for aaa. The nearest a before the last stands 1 from the end; any other letter jumps 3.

    why it is allowed: The text's letter above the pattern's last is always a. The nearest a before the last stands 1 from the end, so the letter a jumps 1. For nn of 1 or 2 the pattern is one a, with no letter before its last, so it jumps its whole length, 1 again. The pattern moves on one place at a time.

  4. the move: the places

    the line:
    places: n−m+1\text{places: } n - m + 1

    why it is allowed: By line 3, every place from 1 to the last, where the pattern's mm letters lie under letters n−m+1n - m + 1 to nn. For 6 letters and 3, places 1 to 4.

  5. the move: the pattern half the text

    the line:
    m is ⌈n2⌉,n−m+1 is ⌊n2⌋+1\begin{gathered} m \text{ is } \lceil \frac{n}{2} \rceil, \\ n - m + 1 \text{ is } \lfloor \frac{n}{2} \rfloor + 1 \end{gathered}

    why it is allowed: The case takes mm as half of nn rounded up. Half of nn rounded up and half rounded down add up to nn, so n−mn - m is half rounded down, and n−m+1n - m + 1 is 1 more. For 6, 3 and 4.

  6. the move: multiply by the places

    the line:
    M=⌈n2⌉(⌊n2⌋+1)M = \lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1)

    why it is allowed: Line 2's mm at each place, times line 4's places, both written in nn by line 5. For 6, 3 times 4, which is 12; for 7, 4 times 4, which is 16.

  7. the move: no search costs more

    the line:
    no text and pattern ofthese lengths cost more\begin{gathered} \text{no text and pattern of} \\ \text{these lengths cost more} \end{gathered}

    why it is allowed: By line 1 no place costs more than mm, and every jump is at least 1. So no search tries more than line 4's places: at most line 6's MM. For 6, 12.

  8. the move: a ceiling

    the line:
    M≤n2M \le n^2

    why it is allowed: For nn of 1 or more: n2\frac{n}{2} is at most nn, and nn is whole, so ⌈n2⌉\lceil \frac{n}{2} \rceil is at most nn. ⌊n2⌋\lfloor \frac{n}{2} \rfloor is a whole number below nn, so ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is at most nn. Multiply the two. For 6, 12 is at most 36.

  9. the move: read the bound

    the line:
    M∈O(n2)M \in O(n^2)

    why it is allowed: By line 8, with the fixed multiple 1.

  10. the move: a floor

    the line:
    M≥n24M \ge \frac{n^2}{4}

    why it is allowed: Rounding up never makes a number smaller, so ⌈n2⌉\lceil \frac{n}{2} \rceil is at least n2\frac{n}{2}. Rounding down takes off less than 1, so ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is more than n2\frac{n}{2}. Multiply the two, as n2\frac{n}{2} times n2\frac{n}{2} is n24\frac{n^2}{4}. For 6, 12 against 9.

  11. the move: read the bound

    the line:
    M∈Ω(n2)M \in \Omega(n^2)

    why it is allowed: By line 10, with the fixed multiple a quarter.

  12. the move: both together

    the line:
    M∈Θ(n2)M \in \Theta(n^2)

    why it is allowed: Lines 9 and 11 bound MM by the same growth.

try it with a small nn: at n=6n = 6, line 6 gives M=12M = 12, which you can work out by hand

Question 3: with the pattern fixed at bbbbb, how many comparisons, JJ, on a text of nn a's?
  1. the move: one comparison, a jump of 5

    the line:
    each place: 1 comparison,then a jump of 5\begin{gathered} \text{each place: 1 comparison,} \\ \text{then a jump of 5} \end{gathered}

    why it is allowed: Question 1's lines 1 and 2 with mm as 5: a, not in the pattern, jumps the whole pattern, 5. The pattern's last b differs from an a at once.

  2. the move: the places tried

    the line:
    places 1,6,11 and on,up to n−4\begin{gathered} \text{places } 1, 6, 11 \text{ and on,} \\ \text{up to } n - 4 \end{gathered}
    nplaces triedcomparisons
    511
    911
    101 and 62
    141 and 62
    151, 6 and 113
    A text of a's and the pattern bbbbb. A place is added each time the text reaches a whole 5 more letters.

    why it is allowed: Each jump adds 5, by line 1. No place past n−4n - 4 fits, question 1's line 3 with mm as 5. For 14 letters, places 1 and 6; place 11 passes place 10.

  3. the move: a place for each 5 letters

    the line:
    J=⌊n5⌋J = \lfloor \frac{n}{5} \rfloor

    why it is allowed: By line 2, a place fits when it is at most n−4n - 4, so place 1 needs 5 letters, place 6 needs 10, and each place after 5 more. So the places are n5\frac{n}{5} rounded down, 1 comparison each by line 1. For 14, 2.

  4. the move: a ceiling

    the line:
    J≤n5J \le \frac{n}{5}

    why it is allowed: Rounding down never makes a number bigger. For 14, 2 against 2.8.

  5. the move: read the bound

    the line:
    J∈O(n)J \in O(n)

    why it is allowed: By line 4, with the fixed multiple a fifth.

  6. the move: a floor

    the line:
    J≥n10J \ge \frac{n}{10}
    nn / 5Jn / 10
    5110.5
    91.810.9
    142.821.4
    193.831.9
    A text of a's and the pattern bbbbb. J never falls below a tenth of n.

    why it is allowed: By line 3. From nn of 5 up, n5\frac{n}{5} is at least 1. Below 2, it rounds down to 1, more than half of it. From 2 up, rounding down takes off less than 1, at most half of it. Either way JJ keeps at least half, n10\frac{n}{10}. For 9, 1 against 0.9.

  7. the move: read the bound

    the line:
    J∈Ω(n)J \in \Omega(n)

    why it is allowed: By line 6, with the fixed multiple a tenth.

  8. the move: both together

    the line:
    J∈Θ(n)J \in \Theta(n)

    why it is allowed: Lines 5 and 7 bound JJ by the same growth. At 10,000 letters, 2,000 comparisons, a fifth of a comparison a letter.

try it with a small nn: at n=10n = 10, line 3 gives J=2J = 2, which you can work out by hand

count it yourself

A text of 6 a's and the pattern aaa, question 2's worst at 6. At each place all 3 letters match from the end, and a jumps 1. A position is a letter's number in the text, from 1.

aaaaaa, aaa, every step written down
stepthe rowwhat happensletters compared
1Look for aaa in aaaaaa. First write a table, from the pattern alone, of how far it may jump.0
21The nearest a before the pattern's last letter stands 1 letter from its end. With a in the text under the pattern's last letter, the pattern may jump 1.10
31, 3Any other letter is nowhere in the pattern before its last letter, so with it under the pattern's last letter the pattern may jump its whole length, 3.1, 30
41, 3The text's a at position 3 matches the pattern's a.1, 31
51, 3The text's a at position 2 matches the pattern's a.1, 32
61, 3The text's a at position 1 matches the pattern's a.1, 33
71, 3Every letter matched: the pattern stands at place 1. Mark it.1, 33
81, 3a is under the pattern's last letter, so the table allows a jump of 1.1, 33
91, 3Jump the pattern on 1 place, to place 2, and compare from its last letter again.1, 33
101, 3The text's a at position 4 matches the pattern's a.1, 34
111, 3The text's a at position 3 matches the pattern's a.1, 35
121, 3The text's a at position 2 matches the pattern's a.1, 36
131, 3Every letter matched: the pattern stands at place 2. Mark it.1, 36
141, 3a is under the pattern's last letter, so the table allows a jump of 1.1, 36
151, 3Jump the pattern on 1 place, to place 3, and compare from its last letter again.1, 36
161, 3The text's a at position 5 matches the pattern's a.1, 37
171, 3The text's a at position 4 matches the pattern's a.1, 38
181, 3The text's a at position 3 matches the pattern's a.1, 39
191, 3Every letter matched: the pattern stands at place 3. Mark it.1, 39
201, 3a is under the pattern's last letter, so the table allows a jump of 1.1, 39
211, 3Jump the pattern on 1 place, to place 4, and compare from its last letter again.1, 39
221, 3The text's a at position 6 matches the pattern's a.1, 310
231, 3The text's a at position 5 matches the pattern's a.1, 311
241, 3The text's a at position 4 matches the pattern's a.1, 312
251, 3Every letter matched: the pattern stands at place 4. Mark it.1, 312
261, 3a is under the pattern's last letter, so the table allows a jump of 1.1, 312
271, 3The pattern would run past the end of the text. It stands at 4 places. That took 12 comparisons.1, 312

In all, 12 letters compared. The formula from section 4, ⌈n2⌉(⌊n2⌋+1)\lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1), gives M=12M = 12 at n=6n = 6: the same.

where you meet it

Horspool cut a famous search down to one table in 1980. Python's own search skips ahead the same way when the text and the pattern are long enough.

  • Horspool's paper

    Boyer and Moore's 1977 search keeps two tables for jumping ahead. Horspool's 1980 paper keeps only the one this page builds, for the text's letter above the pattern's last, and finds it about as fast on ordinary text.

    source: R. N. Horspool, Software: Practice and Experience 10(6), 1980, pages 501 to 506, Practical fast searching in strings (opens in a new tab)

  • Python's find

    CPython, the usual Python, searches text, a str, with its fastsearch code, which joins ideas from Boyer-Moore and from Horspool. When the text and the pattern are both long enough, it jumps by a table for the text's letter above the pattern's last, much as this page does. That jump is one part of a longer method.

    source: CPython's fastsearch, Objects/stringlib/fastsearch.h (opens in a new tab)

  • The books' advice

    The books name Boyer-Moore, Horspool's starting point, for a long pattern over many different letters. A letter nowhere in the pattern skips the whole pattern, and on English text it reads only a fraction of the letters.

    source: the books' volume four, chapter 41

what is used instead

On a repetitive text and pattern, Knuth-Morris-Pratt can cost far less: 10 against 30 on the 10 a's and baaaa, its table included. Brute force needs no table, and can win when the pattern's first letter differs at once but its end matches: 6 against 30 there.

how it compares

The four searches on the watch page's first example, and on 10 a's and baaaa, which cost Horspool as much as its worst at 10. Its table pays on ordinary words and costs on a repeated letter.

methodcomparisonsalso
brute force10
Horspool6
Knuth-Morris-Pratt14its table included
Rabin-Karp67 fingerprints
toothpaste and paste, each method's own count. Horspool reads 6 letters of the 10.
methodcomparisonsalso
brute force6
Horspool30
Knuth-Morris-Pratt10its table included
Rabin-Karp07 fingerprints
10 a's and baaaa. Brute force's first letter, b, differs at once; Horspool starts from the a's at the end. Rabin-Karp's fingerprints never agree, so it compares no letter.

race them on one row of your own