Chapter 16: Searching Algorithms
16.01Beginner / Intermediate4 topics12 min2 interactive animations

Sequential search

Sequential search walks a collection one element at a time. It is the only general option when the data has no order, and it is the baseline every faster search is measured against.

Learning goals

  • Trace linear search step by step and count its comparisons
  • Explain how a sentinel removes the bounds check from the loop
  • State best, average and worst case cost and when each happens
  • Search unsorted Java arrays and collections correctly, including objects

Prerequisites

Arrays and indexingfor and while loopsBig-O notation

Looking for a name on an unsorted guest list means reading names one by one, because nothing tells you where to jump. That is sequential search.

16.01.3

Best/average/worst case

The cost of linear search depends on where the target is. We count comparisons because they dominate the work.

If the target is present and every position is equally likely, the expected number of comparisons is (1 + 2 + … + n) / n = (n + 1) / 2, which is still O(n).

CaseWhen it happensComparisonsBig-O
BestTarget is at index 01O(1)
Average (present)Target equally likely anywhere(n + 1) / 2O(n)
Worst (present)Target is the last elementnO(n)
AbsentTarget is not in the arraynO(n)

Practice ladder

Now try it yourself

Easy

  • Return the index of the last occurrence of a target
  • Count how many times a value appears
  • Find the maximum element and its index

Medium

  • Find the first element greater than a given value
  • Search a 2D grid row by row and return [row, col]
  • Return all indices where the target occurs

Advanced

  • Implement sentinel search for String[] using equals()
  • Benchmark plain vs sentinel search with JMH
  • Find the first non-repeating element in one pass plus a map

Key takeaways

  • Linear search is O(n) time and O(1) space, and it works on any order.
  • A sentinel removes the per-iteration bounds check at the cost of temporarily mutating the array.
  • For objects, compare with equals(); for repeated lookups, switch to hashing or sorting.