2.2.19 Linear Search in an Array

Search Round Scores from the Beginning

A linear search examines array positions in order until it finds a match or reaches the end. The Wildcats coach wants the first round that recorded zero goals.

Explore the Soccer Example

The local foundIndex uses -1 to mean no match has been found. Valid indexes are nonnegative, so -1 cannot be mistaken for a matching position.

Search Round Scores from the Beginning
int[] roundGoals = { 2, 0, 3 };
int target = 0;
int foundIndex = -1;

for (int index = 0; index < roundGoals.Length; index++)
{
    if (roundGoals[index] == target)
    {
        foundIndex = index;

        break;
    }
}
Check the Values
Worked soccer example
Position examined Score Matches zero? Action
0 2 No Continue
1 0 Yes Store 1 and break
2 3 Not examined Search already ended
Understand the Code

Compare the current element with the target

The first pass reads score 2 from index 0. It does not equal target 0, so the body of the if is skipped. The loop update advances index to 1.

Save the position of the first match

At index 1, the score is 0. The condition is true, so the program stores 1 in foundIndex.

The result is an index, not the matched score. It tells where the coach's requested score was found.

Stop the search once the required answer is known

Break leaves the loop immediately after saving the index. Index 2 is not examined. The header update also does not execute on that early-exit pass.

This search returns the first match because it stops as soon as it finds one.

Keep the no-match result if all checks fail

If the target were 5, every element comparison would be false. The loop would finish normally and foundIndex would stay -1.

Do not use -1 as an element index afterward. It is the marker for an unsuccessful search.

Keep a matching position distinct from the target value

The target is zero goals, but the result for the shown scores is index 1. Storing the matched score instead of the index would lose the location the coach asked to find.

The marker -1 also needs interpretation before any later access. It reports failure; it is not a request to read the element before index zero.

Try a Small Change
Predict the Result
Use the Original Diagram to Check Your Reasoning

The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.

Search Round Scores from the Beginning.
Search Round Scores from the Beginning
  • New
  • Changed
  • Removed

The matching branch stores the current index and exits the loop. The nonmatching branch reaches index++ and checks the next position. Both a match exit and an exhausted-array exit lead to the final node, but foundIndex distinguishes their results.