Searching Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Searching.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

The process of locating a specific item or value within a collection of data using a systematic strategy.

Looking for a book on a shelf, a name in a list, a file on your computer.

Read the full concept explanation β†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: The best search strategy depends on whether the data is sorted and how large the collection is.

Common stuck point: Binary search requires sorted dataβ€”but is much faster than linear search.

Worked Examples

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).

Example 2

medium
Use binary search to find 23 in the sorted list [5, 10, 15, 20, 23, 30, 35]. Show each step.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
Can binary search be used on the unsorted list [8, 2, 5, 1, 9]? Why or why not?

Example 2

hard
A sorted list has 128 elements. In the worst case, about how many comparisons does binary search need, and how does that compare with linear search?

Background Knowledge

These ideas may be useful before you work through the harder examples.

arrayalgorithm