Linear Search

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Yes.

Linear Search

When you answered the question, you probably looked over the items one at a time until you found "Peoria". This is roughly the algorithm known as linear search.

Here is a description of linear search:

  • Starting Conditions: You have an array of items and a target.
  • Goal: Find the target in the array of items, or report if the target is not present.
  • Procedure: Look through the cells of the array one by one, starting with the first cell and ending when either the target is found or every cell has been examined.
  • Result: Where the target was found, or a indication that it was not found.
    • For this example: Return the index where the target was found, or -1 if the target was not found.

Look over the array of Strings. Apply the algorithm. Is "Peoria" in the array? Is "Albany" in the array? Is "Mystic" in the array?

01234567
Boston Albany Detroit Phoenix Peoria Albany Houston Hartford

QUESTION 14:

Now consider these questions:

  • Do the cities have to be in order?
  • Does it hurt that "Albany" is in the array twice?