Brute-force search
how it works
The idea on the watch page's first example, bag in cabbage. Then the whole method on it, step by step.
Look for bag in cabbage. Put bag under the text's first letter and compare from the left. c is not b, so move bag on one place. a is not b: move on. At place 3, b matches b, then b is not a: move on. At place 4, b, a and g all match, so bag stands at place 4. Its b is the text's letter 4, which place 3 read already: brute force reads some letters more than once. At place 5, a is not b. Every place is tried. That is the whole method. Try every place, compare from the left until a letter differs, then move on one. 7 letters and 3 give 7 - 3 + 1, which is 5 places. They cost 1 + 1 + 2 + 3 + 1, which is 8 comparisons. The code below counts places from 0 and returns them in a list, so it returns [3].
| place | letters above | matched | comparisons |
|---|---|---|---|
| 1 | cab | 0 | 1 |
| 2 | abb | 0 | 1 |
| 3 | bba | 1 | 2 |
| 4 | bag | 3, a match | 3 |
| 5 | age | 0 | 1 |
| all | 8 |
step 1 of 19
Look for bag in cabbage. The pattern can stand at 5 places, so try each in turn, starting under the first letter.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- not yet
Where it says not yet, nothing is held there at that moment.
step 3 of 19
No letter matched at place 1. Write it in the table.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- 0
step 9 of 19
The text's b at position 4 is not the pattern's a, so the pattern does not stand here.
what it remembers to know where it is
- pattern stands at place
- 3
- letters matched here
- 1
step 10 of 19
1 letter matched at place 3. Write it in the table.
what it remembers to know where it is
- pattern stands at place
- 3
- letters matched here
- 1
step 15 of 19
Every letter matched: the pattern stands at place 4. Mark it and write it in the table.
what it remembers to know where it is
- pattern stands at place
- 4
- letters matched here
- 3
step 19 of 19
Every place has been tried. The pattern stands at 1 place. That took 8 comparisons.
what it remembers to know where it is
- pattern stands at place
- 5
- letters matched here
- 0
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- for each place the pattern can stand, from the start of the textPython line 9
- compare its letters with the text's, from the left, until one differsPython lines 11, 12 and 13
- write how many matched; if all of them did, mark a matchPython lines 14 and 15
- move the pattern on one placePython line 9
- every place tried, so every match is foundPython line 16
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 brute_force_search(text, pattern):
"""Find every place a pattern stands in a text, by trying them all.
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)
places = []
for place in range(n - m + 1): # each place the pattern can stand, from the start
matched = 0
# compare its letters with the text's, from the left, until one differs
while matched < m and text[place + matched] == pattern[matched]:
matched += 1
if matched == m: # every letter matched
places.append(place) # so it stands here
return places # every place tried: every match found
how it scales
The plot counts the comparisons on a text of letters and a pattern half as long, rounded up, in two ways. The best never matches a first letter. The worst matches every letter but the last, at every place. Measured from 10 to 10,000.
Each mark across or up is ten times the one before. The best line climbs one mark up for each mark across: 51 comparisons at 100 letters, 501 at 1,000. 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
, 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 ending in b, 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
| letters compared | time | |
|---|---|---|
| 1,000 | 250,500 | about 251 microseconds |
| 100,000 | 2,500,050,000 | about 2.5 seconds |
| 10,000,000 | 25,000,005,000,000 | about 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 brute-force search'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 first letter differs at every place, the fewest; and a's
ending in one b, so every letter is compared at every place, 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 brute_force_search(text, pattern):
"""Find every place a pattern stands in a text, by trying them all.
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)
places = []
for place in range(n - m + 1): # each place the pattern can stand, from the start
matched = 0
# compare its letters with the text's, from the left, until one differs
while matched < m and text[place + matched] == pattern[matched]:
matched += 1
if matched == m: # every letter matched
places.append(place) # so it stands here
return places # every place tried: every match found
def count(text, pattern):
"""How many comparisons brute_force_search makes: one for each letter
of the text it compares with a letter of the pattern."""
n, m = len(text), len(pattern)
compared = 0
for place in range(n - m + 1):
matched = 0
while matched < m:
compared += 1
if text[place + matched] != pattern[matched]:
break
matched += 1
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 letters, rounded up,
all a but the last, which is b."""
return "a" * n, "a" * ((n + 1) // 2 - 1) + "b"
if __name__ == "__main__":
print(f"{'n':>7} {'all b':>8} {'a ending b':>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, letters and . Section 4's question 3 shows that length can cost the most. Both have the same places, , by section 4's question 1; only the letters differ. For 6 letters and 3: 4 places, 4 comparisons at best and 12 at worst. 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 1,000 letters the worst is 500 times 501: 500 times 500, which is 250,000, plus 500. They are the pieces and , 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.
| besta text of a's and a pattern of b's, half as long | worsta text of a's and a pattern of a's ending in b, half as long | |
|---|---|---|
| letters compared | ||
| how the letters compared grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: two numbers, the place and how many letters matched, beside the places found
Extra memory is the room it needs on top of the input itself, while it runs.
| text | pattern | places | comparisons |
|---|---|---|---|
| cabbage | bag | 5 | 8 |
| banana | ana | 4 | 8 |
| breakfast | quick | 5 | 5 |
| aaaaaaaaaa | aaaab | 6 | 30 |
| n | best | worst |
|---|---|---|
| 6 | 4 | 12 |
| 7 | 4 | 16 |
| 10 | 6 | 30 |
where the formula comes from
Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 shows why the pattern is half the text.
the move: the places
the line:place under letters 1 1 to 3 2 2 to 4 3 3 to 5 4 4 to 6 A pattern of 3 under a text of 6. At place 4 its last letter is under letter 6, so there is no place 5. why it is allowed: The pattern is first tried under the text's letter 1. At its last place, its last letter is under the text's last, , and its letters cover letters to . For 6 letters and 3, places 1 to 4.
the move: this page's pattern
the line:why it is allowed: The cases take a pattern half as long as the text, rounded up, as its . Question 3 shows why. For 6, 3; for 7, 4.
guess it, thenthe move: one comparison a place
the line:place letters above against comparisons 1 aaa bbb 1 2 aaa bbb 1 3 aaa bbb 1 4 aaa bbb 1 all 4 A text of 6 a's and the pattern bbb. At each of the 4 places, a is not b at once. 4 places, 4 comparisons. why it is allowed: The text is all a and the pattern all b. At each place the first comparison differs, and the pattern moves on. So one comparison at each place of line 1, with line 2's . For 6, 4.
guess it, thenthe move: half, rounded down
the line:why it is allowed: Half of rounded up and half of rounded down add up to . So less the first leaves the second. For 6, 3 and 3; for 7, 4 and 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, half of rounded down is a whole number below , so at most the whole number just below . Adding 1 gives at most . For 1, 0 + 1 is 1, exactly ; for 6, 4.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: Rounding down takes off less than 1, so line 4's is more than . For 7, 4 against 3.5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 7, with the fixed multiple a half.
guess it, thenthe move: both together
the line:why it is allowed: Lines 6 and 8 bound by the same growth.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a place's most
the line:why it is allowed: At a place the pattern's letters are compared from the left, one each, until one differs. It has letters, so at most .
the move: every letter but the last matches
the line:place letters above against comparisons 1 aaa aab 3 2 aaa aab 3 3 aaa aab 3 4 aaa aab 3 all 12 A text of 6 a's and the pattern aab. At each of the 4 places, a and a match, then b differs. 4 times 3 is 12. why it is allowed: The text is all a, and so is every letter of the pattern but the last. Those match at every place, and the last, b, differs. So all letters are compared at every place.
guess it, thenthe move: multiply by the places
the line:why it is allowed: By line 2, comparisons at each place, with as by section 4's question 1, line 2. Question 1 made one comparison at each place, in all, by its lines 3 and 4, so there are places. Multiply the two. For 6, 3 times 4, which is 12; for 7, 4 times 4, which is 16.
guess it, thenthe move: a ceiling
the line:why it is allowed: Half of is at most , a whole number, so rounding it up stays at most . is at most by section 4's question 1, line 5. Multiply the two. For 6, 12 is at most 36.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: Rounding up never makes a number smaller, so is at least . By section 4's question 1, line 7, is more than . Multiply the two, as times is . For 6, 12 against 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple a quarter.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a ceiling for one length
the line:m places at most 1 6 6 2 5 10 3 4 12 4 3 12 5 2 10 6 1 6 A text of 6 letters, every pattern length. The ceiling climbs to 12 at 3 and 4 letters, then falls. why it is allowed: At most comparisons at a place, by question 2's line 1, and places, by question 1's line 1. Multiply the two. For 6 letters and 3, 3 times 4, which is 12.
the move: a fixed sum
the line:why it is allowed: Line 1's and its places, , add up to , whatever is. For 6, 3 and 4 make 7, and so do 2 and 5.
guess it, thenthe move: even out the parts
the line:why it is allowed: Take two parts and , at least 2 more than . Move 1 from to ; the sum stays the same, and multiplying out gives the line. is at least 1, so the product grows. For 5 and 2, 4 times 3 is 12, more than 10.
guess it, thenthe move: the most
the line:why it is allowed: By line 3, while the parts are 2 or more apart, their product can still grow. By line 2 they add up to . and add up to too, by question 1's line 4, and they are at most 1 apart, so they are the closest, either way round. For 6, 3 and 4, 12; for 7, 4 and 4, 16.
guess it, thenthe move: the most of any length
the line:why it is allowed: By line 4, multiply the two closest parts. That is , the most line 1's ceiling reaches, so a pattern of letters has the highest ceiling of any length. For an even , one letter more ties it, as 4 letters do for 6.
guess it, thenthe move: no search costs more
the line:why it is allowed: By lines 1 and 5, no pattern on a text of letters costs more than . Question 2's line 3 is the same product, so its text and pattern meet it, and is the most. For 6, 12.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
count it yourself
A text of 6 a's and the pattern aab, question 2's worst at 6. At each place a and a match, then b differs. A position is a letter's number in the text, from 1. The second column lists how many letters matched at each place so far; the last column is a running total.
| step | the row | what happens | letters compared |
|---|---|---|---|
| 1 | Look for aab in aaaaaa. The pattern can stand at 4 places, so try each in turn, starting under the first letter. | 0 | |
| 2 | The text's a at position 1 matches the pattern's a. | 1 | |
| 3 | The text's a at position 2 matches the pattern's a. | 2 | |
| 4 | The text's a at position 3 is not the pattern's b, so the pattern does not stand here. | 3 | |
| 5 | 2 | 2 letters matched at place 1. Write it in the table.2 | 3 |
| 6 | 2 | Move the pattern on one place, to place 2, and start again from its first letter.2 | 3 |
| 7 | 2 | The text's a at position 2 matches the pattern's a.2 | 4 |
| 8 | 2 | The text's a at position 3 matches the pattern's a.2 | 5 |
| 9 | 2 | The text's a at position 4 is not the pattern's b, so the pattern does not stand here.2 | 6 |
| 10 | 2, 2 | 2 letters matched at place 2. Write it in the table.2, 2 | 6 |
| 11 | 2, 2 | Move the pattern on one place, to place 3, and start again from its first letter.2, 2 | 6 |
| 12 | 2, 2 | The text's a at position 3 matches the pattern's a.2, 2 | 7 |
| 13 | 2, 2 | The text's a at position 4 matches the pattern's a.2, 2 | 8 |
| 14 | 2, 2 | The text's a at position 5 is not the pattern's b, so the pattern does not stand here.2, 2 | 9 |
| 15 | 2, 2, 2 | 2 letters matched at place 3. Write it in the table.2, 2, 2 | 9 |
| 16 | 2, 2, 2 | Move the pattern on one place, to place 4, and start again from its first letter.2, 2, 2 | 9 |
| 17 | 2, 2, 2 | The text's a at position 4 matches the pattern's a.2, 2, 2 | 10 |
| 18 | 2, 2, 2 | The text's a at position 5 matches the pattern's a.2, 2, 2 | 11 |
| 19 | 2, 2, 2 | The text's a at position 6 is not the pattern's b, so the pattern does not stand here.2, 2, 2 | 12 |
| 20 | 2, 2, 2, 2 | 2 letters matched at place 4. Write it in the table.2, 2, 2, 2 | 12 |
| 21 | 2, 2, 2, 2 | Every place has been tried. The pattern stands nowhere in the text. That took 12 comparisons.2, 2, 2, 2 | 12 |
In all, 12 letters compared. The formula from section 4, , gives at : the same.
where you meet it
The books' dispatcher searches a courier's log this way. So does Java's plain search. A paper on a faster search opens with this method's worst case.
The dispatcher's log
The books give a dispatcher a courier's afternoon, 28 stops, one letter each, to search for a run of 6. This method makes 58 comparisons, and 32 of them read a letter it has read before.
source: the books' volume four, chapter 41
Java's indexOf
Java is a programming language, and OpenJDK is its free reference version. Its String.indexOf, in plain Java, finds the pattern's first letter in the text, then compares the rest. When a letter differs, it moves on one place, as this page does.
source: OpenJDK's indexOf and indexOf0, in the java.base module, java/lang/StringLatin1.java (opens in a new tab)
A faster search
Knuth, Morris and Pratt's 1977 paper gives this method's worst case as its first example, a pattern of a's ending in b. It gives a method that never steps back in the text, its comparisons growing with the two lengths added.
source: D. E. Knuth, J. H. Morris and V. R. Pratt, SIAM Journal on Computing 6(2), 1977, pages 323 to 350, Fast pattern matching in strings (opens in a new tab)
what is used instead
On a long or repetitive text, study the pattern first. Knuth-Morris-Pratt never steps back in the text. Horspool jumps ahead by a table of letters. Rabin-Karp compares fingerprints first. The books cover the first and the third.
how it compares
Three rivals study the pattern before they look at the text. On the watch page's dearest example, each makes fewer comparisons, Horspool and Rabin-Karp far fewer.
| method | studies first | worst comparisons |
|---|---|---|
| brute force | nothing | , at most |
| Horspool | a jump for each letter | the same |
| Knuth-Morris-Pratt | the pattern against itself | at most twice the two lengths added |
| Rabin-Karp | the pattern's fingerprint | the same |
| method | comparisons | also |
|---|---|---|
| brute force | 30 | |
| Horspool | 6 | |
| Knuth-Morris-Pratt | 22 | its table included |
| Rabin-Karp | 0 | 7 fingerprints |