7.4 Searching Algorithms

The act of searching is a common activity for humans as well as computers. When you look for a name in a directory, for instance, you are performing a search. We explore two search algorithms in this section.

Sequential Search

Our first searching algorithm follows the most straightforward concept of a search. We look at each item in turn and compare it to the one for which we are searching. If it matches, we have found the item. If not, we look at the next item. We stop either when we have found the item or when we have looked at all the items and not found a match. This sounds like a loop with two ending conditions. Let’s write the algorithm using the array numbers.

Get Computer Science Illuminated, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.