liveBook · Manning

Compare algorithm

As explained in How Computers Make Books

A compare algorithm is a procedure that compares a word with text at specified positions and returns whether the compared characters all match.

To find a word in a longer line of text, first ask a small question at one possible starting position: do all the letters match? A compare algorithm answers that question with true or false. It receives a text position and a word position, then checks corresponding characters. section 4.2

The procedure stops successfully when it has reached the word’s length: every character has matched. Otherwise, if the current text character equals the current word character, it advances both positions and compares again. A mismatch returns false immediately. section 4.2

Finding “horses”

With W = “horses” and T = “houses and horses and hearses”, search calls compare at each possible position. Compare returns true at position 11, so search prints 11; it returns false at positions whose characters diverge. section 4.2

Figure 4.2 Each comparison in our search

Trace the individual character comparisons made while testing each possible starting position. section 4.2

How How Computers Make Books covers it

How deep it goes
Works through termination, one-character comparison, advancement, and immediate failure in pseudocode.
Examples
Traces searches for “horses” in “houses and horses and hearses,” including the match at position 11.
What you can do after
Build it from scratch as a character-by-character predicate used by a search procedure.
How it connects
Connects text search with functions, parameters, conditional tests, recursion, and modular programming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of How Computers Make Books. The section links point to the parts of the book it draws on.