Searching CS Thinking Example 1

Follow the full solution, then compare it with the other examples linked below.

Example 1

medium
Use linear search to find the value 7 in the list [3, 9, 7, 1, 5]. How many comparisons are needed?

Solution

  1. 1
    Step 1: Compare 3 with 7 โ€” no match. Compare 9 with 7 โ€” no match.
  2. 2
    Step 2: Compare 7 with 7 โ€” match found at index 2.
  3. 3
    Step 3: 3 comparisons were needed.

Answer

Found at index 2 after 3 comparisons.
Linear search checks elements one by one from the start. It works on any list (sorted or unsorted) but can be slow for large lists โ€” worst case is O(n)O(n).

About Searching

The process of locating a specific item or value within a collection of data using a systematic strategy. The two fundamental approaches are linear search (check every element one by one) and binary search (repeatedly halve the search space in sorted data).

Learn more about Searching โ†’

More Searching Examples