Name
  • String
  • Substring
  • Search
Edit

The bad-character shift used in the Boyer-Moore algorithm (see chapter Boyer-Moore algorithm) is not very efficient for small alphabets, but when the alphabet is large compared with the length of the pattern, as it is often the case with the ASCII table and ordinary searches made under a text editor, it becomes very useful.
Using it alone produces a very efficient algorithm in practice. Horspool proposed to use only the bad-character shift of the rightmost character of the window to compute the shifts in the Boyer-Moore algorithm.

The preprocessing phase is in O(m+sigma) time and O(sigma) space complexity.

The searching phase has a quadratic worst case but it can be proved that the average number of comparisons for one text character is between 1/sigma and 2/(sigma+1).


Main features:

  • simplification of the Boyer-Moore algorithm;
  • easy to implement;
  • preprocessing phase in O(m+sigma) time and O(sigma) space complexity;
  • searching phase in O(mn) time complexity;
  • the average number of comparisons for one text character is between 1/ and 2/(+1).

Example:

Preprocessing phase

Horspool algorithm bmBc table
bmBc table used by Horspool algorithm

Searching phase

First attempt
GCATCGCAGAGAGTATACAGTACG
 1 
GCAGAGAG 

Shift by: 1 (bmBc[A])

Second attempt
GCATCGCAGAGAGTATACAGTACG
 2      1 
 GCAGAGAG 

Shift by: 2 (bmBc[G])

Third attempt
GCATCGCAGAGAGTATACAGTACG
 2      1 
 GCAGAGAG 

Shift by: 2 (bmBc[G])

Fourth attempt
GCATCGCAGAGAGTATACAGTACG
 23456781 
 GCAGAGAG 

Shift by: 2 (bmBc[G])

Fifth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Shift by: 1 (bmBc[A])

Sixth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Shift by: 8 (bmBc[T])

Seventh attempt
GCATCGCAGAGAGTATACAGTACG
 2      1
 GCAGAGAG

Shift by: 2 (bmBc[G])

The Horspool algorithm performs 17 character comparisons on the example.

C