2.2.19 Linear Search in an Array

Overview

A linear search checks array items in order until it finds a target or reaches the end. An index can record the matching position. Initialize it to -1 to mean no match has been found yet.

string[] names = { "Ana", "Bo", "Cy" };
int foundIndex = -1;
for (int i = 0; i < names.Length; i++)
{
    if (names[i] == "Bo")
    {
        foundIndex = i;
        break;
    }
}
Check Items Until a Match
Activity diagram for linear search in an array: check items until a match.
Check Items Until a Match
  • New
  • Changed
  • Removed

The first comparison fails; the second succeeds and stores 1. Break exits the loop before checking Cy. If the target were absent, foundIndex would remain -1 after all three checks. Never use -1 as an array index.

This search returns the first matching position because it exits as soon as a match is found. If duplicate values exist, later matches remain unvisited.

Trace the Outcome

Trace the target Bo and an absent target Dee. Count how many comparisons occur and identify the final foundIndex for each.