M05 · Arrays

Traversal and Linear Search

Most array algorithms are one loop over the elements with a little state on the side. This lesson names the handful of traversal patterns that keep coming back, from running totals to early exit and adjacent pairs, shows how to write them without off-by-one errors in four languages, and explains why changing an array while you walk it goes wrong.

~25 minBeginnerC# · Python · Java · C++
Curriculum: M05 Arrays · 5 of 5 lessons available

You will be able to

  • Write forward, backward and index-free traversals and say when each is the right choice.
  • Use the accumulator pattern for sums, counts, minimum and maximum, including the empty-array case.
  • Recognise a linear search as a traversal with an early exit, and find the first, the last or every match.
  • Visit adjacent pairs and fixed strides without reading outside the array.
  • Explain what happens when a collection is modified during iteration in C#, Python, Java and C++, and how to avoid it.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A traversal visits every element of an array once, in some order, and carries a little state from one element to the next: a running total, the best value so far, whether a match has been seen. Nearly every array algorithm in the early modules is a traversal with a different piece of state, and the later patterns (two pointers, sliding windows, prefix sums) are traversals with two positions or with state that is itself an array.

The lab on this page runs the simplest traversal that can stop early: a linear search. Every step either checks the loop condition or compares one element. The searching module's linear search lesson analyses that algorithm in depth (preconditions, comparison counts, sentinels). This lesson is about the loop shapes around it.

Three ways to write the loop

for i from 0 to n - 1:        # by index, forwards: you know where you are
for i from n - 1 down to 0:   # by index, backwards
for each x in a:              # index-free: you only need the values
By index Index-free
C# for (int i = 0; i < a.Length; i++) foreach (var x in a)
Python for i in range(len(a)), better for i, x in enumerate(a) for x in a
Java for (int i = 0; i < a.length; i++) for (int x : a)
C++ for (std::size_t i = 0; i < a.size(); ++i) for (int x : a), or const auto& for large elements

Use the index-free form when you only need values: it cannot go out of bounds and states intent. Use an index when the position matters (the result is an index, you compare neighbours, or you write back). Python's enumerate gives both. Backwards is reversed(a) in Python, a.rbegin()…a.rend() or std::views::reverse in C++, and an index loop elsewhere.

A C++ trap for backwards loops: for (std::size_t i = n - 1; i >= 0; --i) never ends, because an unsigned i is always >= 0, and when n == 0 it starts at a huge value. Write for (std::size_t i = n; i-- > 0;) or use a signed index.

Pattern 1: accumulate

Carry one value through the loop and combine each element into it:

total = 0                     # sum: start at the identity element
for each x in a: total += x

best = a[0]                   # maximum: start at the first element (needs n >= 1)
for i from 1 to n - 1:
    if a[i] > best: best = a[i]

The starting value is the part people get wrong. A sum starts at 0 and a product at 1. A maximum has no neutral starting value unless you pick the smallest possible one (int.MinValue, Integer.MIN_VALUE, std::numeric_limits<int>::min(), -math.inf), which then gets returned for an empty array as if it were data. Starting from a[0] and failing on empty input is usually more honest. The built-ins make that choice explicit: Python's max([]) raises ValueError unless you pass default=; C#'s Enumerable.Max throws on an empty sequence of int; Java's IntStream.max() returns an empty OptionalInt; C++'s std::max_element returns the end iterator.

Counting (if condition: count += 1) and "does any / do all elements satisfy p" are accumulators too. any can stop at the first true and all at the first false, which leads to the next pattern.

When the answer is decided before the end, stop:

for i from 0 to n - 1:
    if a[i] == target: return i      # first match: stop here
return -1                            # looked at everything

That is linear search, and the lab traces it. Its cost depends on where the first match is: one comparison if it is at index 0, n if it is missing. Run the Not found preset to see the full n comparisons plus the final failing bounds check. Proving absence always costs a full traversal on unsorted data; only extra structure (sorted order, a hash set) can avoid that.

Variants of the same loop:

  • Last match: traverse backwards and return the first match, or traverse forwards and remember the latest match without stopping.
  • Every match: traverse without stopping and collect the indices.
  • Predicate search: compare with any condition, not just equality: Array.FindIndex, next((i for i, x in enumerate(a) if p(x)), -1), IntStream.range(0, n).filter(...).findFirst(), std::find_if.

Pattern 3: adjacent pairs and strides

To compare each element with its neighbour, the loop must stop one early:

for i from 1 to n - 1:               # pairs (a[i-1], a[i]); none when n < 2
    if a[i - 1] > a[i]: return "not sorted"

Starting at 1 and reading a[i − 1] keeps every access in range, including for n = 0 and n = 1, where the loop body never runs. The alternative for i in 0 … n − 2 with a[i + 1] is equivalent but its bound n − 2 underflows with unsigned sizes in C++. Python has itertools.pairwise(a) (3.10+) and C++23 has std::views::adjacent<2> and std::views::pairwise.

A stride visits every k-th element: for i in range(0, n, k), for (int i = 0; i < n; i += k). It is the shape of the jump search in the searching module and of reading one column of a matrix stored row by row.

Pattern 4: two arrays in step

Walk two arrays with one index (zip(a, b) in Python, Enumerable.Zip in C#, std::views::zip in C++23) or with two independent indices that advance at different times, as when merging two sorted arrays. The second form is the two-pointer technique, which has its own lesson.

Modifying while traversing

Changing an array's values during a loop is fine. Changing its size is where traversals break:

Language Adding or removing elements during foreach / iteration
C# List<T>'s enumerator throws InvalidOperationException on the next step ("Collection was modified"). Arrays cannot change size.
Python No error for lists: removing during for x in a silently skips the element after each removed one; appending can loop forever. (Dicts and sets raise RuntimeError if their size changes.)
Java ArrayList's iterator throws ConcurrentModificationException on a best-effort basis; Iterator.remove() is the supported way to remove.
C++ vector::erase and push_back invalidate iterators (at and after the position, or all of them on reallocation); using one afterwards is undefined behaviour.

Safe alternatives, in order of preference: build a new array ([x for x in a if keep(x)], LINQ Where, streams, std::copy_if); compact in place with a read index and a write index (RemoveAll, removeIf, std::erase_if); or iterate backwards by index when deleting, so the deletions only shift elements you have already visited.

Costs

Pattern Time Extra space
Full traversal (sum, count, min, max) Θ(n) O(1)
Early-exit search O(n) worst, O(1) best O(1)
Adjacent pairs, strides Θ(n), Θ(n / k) O(1)
Collect every match Θ(n) O(m) for m matches
Filter into a new array Θ(n) O(n)

These assume O(1) access to each element, which arrays give you. Index-based loops over a linked list would cost O(n²) in total, because reaching index i is O(i); the index-free form is O(n) on both.

The teaching implementation

The four listings below are the linear search from the searching module: an index loop, an equality test, an early return i, and return -1 after the loop. They are the same files the lab highlights, tested against one shared fixture and against each language's built-in search (Array.IndexOf, list.index, List.indexOf, std::find). The other patterns in this lesson are short enough to write from the tables above; the built-ins named there are what production code should use.

Common mistakes

  • i <= n in the loop condition: one access past the end.
  • Starting a maximum at 0: wrong for all-negative arrays. Start at a[0] or at the type's minimum, and decide what an empty array returns.
  • Forgetting the early exit, or exiting on the first non-match in a search.
  • Unsigned countdown loops in C++ that never terminate.
  • Removing elements inside foreach: an exception in C# and Java, skipped elements in Python, undefined behaviour in C++.

Edge cases

  • Empty array: loops run zero times; sums are 0, searches return -1, minimum and maximum are undefined.
  • One element: no adjacent pairs; it is both the minimum and the maximum.
  • All elements equal: the first-match search returns 0; a last-match search returns n − 1.
  • Duplicates of the target: decide whether you want the first, the last or all of them.

Worked practice

1. Write a loop that returns the index of the largest element (the first one if it occurs several times). What should it do for an empty array?

Answer
if n == 0: error (or return -1)
best = 0
for i from 1 to n - 1:
    if a[i] > a[best]: best = i     # strict >: keeps the first of equal maxima
return best

Using >= would return the last of several equal maxima.

2. How many element comparisons does a first-match linear search make on [4, 9, 4, 1] for 1, for 4, and for 7?

Answer

For 1: 4 (it is the last element). For 4: 1 (index 0). For 7: 4 (every element, then the loop ends).

3. In Python, a = [1, 2, 2, 3] and for x in a: if x == 2: a.remove(x). What is a afterwards?

Answer

[1, 2, 3]. Removing the first 2 shifts the second 2 into the current position, and the loop's internal index moves past it. Use a = [x for x in a if x != 2].

4. Check whether an array is sorted in ascending order, without ever reading outside it, for any n ≥ 0.

Answer
for i from 1 to n - 1:
    if a[i - 1] > a[i]: return false
return true

For n = 0 or 1 the loop does not run and the array is (trivially) sorted.

Summary

  • Traversals visit each element once and carry a small piece of state; most array algorithms are one.
  • Prefer index-free loops when positions do not matter; use an index (or enumerate) when they do.
  • Accumulators need a correct starting value and a decision about empty input.
  • Linear search is a traversal with an early exit; first, last, all and predicate searches are small variations. The linear search lesson covers its analysis.
  • Adjacent-pair loops start at 1 and read a[i − 1].
  • Never change an array's size while iterating it; build a new one, compact in place, or go backwards.

Full implementation

Linear search in four languages, each checked against one shared fixture (empty, one element, first, last, duplicates, missing, extremes) including the exact number of comparisons, and 2,000 random arrays compared with the language's built-in search (Array.IndexOf, list.index, List.indexOf, std::find).

namespace Bekadan.Dsa.Examples.Searching;
 
/// <summary>
/// Linear search with an early exit: the index of the first element equal to
/// the target, or -1. Works on unsorted data. O(n) comparisons in the worst
/// case, 1 in the best; O(1) extra space.
/// </summary>
public static class LinearSearch
{
    public static int IndexOf<T>(T[] items, T target, IEqualityComparer<T>? comparer = null)
    {
        comparer ??= EqualityComparer<T>.Default;
        for (int i = 0; i < items.Length; i++)
        {
            if (comparer.Equals(items[i], target))
            {
                return i; // the first match: stop early
            }
        }
        return -1; // compared every element
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/LinearSearch.cs

"""Linear search with an early exit.
 
Returns the index of the first element equal to the target, or -1. Works on
unsorted data. O(n) comparisons in the worst case, 1 in the best; O(1) extra
space.
"""
 
import operator
from collections.abc import Callable, Sequence
from typing import Any
 
 
def linear_search(items: Sequence[Any], target: Any, equals: Callable[[Any, Any], bool] = operator.eq) -> int:
    for i in range(len(items)):
        if equals(items[i], target):
            return i  # the first match: stop early
    return -1  # compared every element

Tested on CPython 3.14.0 · examples/python/dsa_examples/linear_search.py

package dev.bekadan.dsa.searching;
 
import java.util.Objects;
import java.util.function.BiPredicate;
 
/**
 * Linear search with an early exit: the index of the first element equal to
 * the target, or -1. Works on unsorted data. O(n) comparisons in the worst
 * case, 1 in the best; O(1) extra space.
 */
public final class LinearSearch {
    private LinearSearch() {
    }
 
    public static <T> int indexOf(T[] items, T target) {
        return indexOf(items, target, Objects::equals);
    }
 
    public static <T> int indexOf(T[] items, T target, BiPredicate<? super T, ? super T> equals) {
        for (int i = 0; i < items.length; i++) {
            if (equals.test(items[i], target)) {
                return i; // the first match: stop early
            }
        }
        return -1; // compared every element
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/LinearSearch.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
 
namespace bekadan::dsa {
 
// Linear search with an early exit: the index of the first element equal to
// the target, or -1. Works on unsorted data. O(n) comparisons in the worst
// case, 1 in the best; O(1) extra space. (std::find does the same with iterators.)
 
template <typename T, typename Equal = std::equal_to<>>
std::ptrdiff_t linear_search(std::span<const T> items, const T& target, Equal equal = {}) {
    for (std::size_t i = 0; i < items.size(); ++i) {
        if (equal(items[i], target)) {
            return static_cast<std::ptrdiff_t>(i);  // the first match: stop early
        }
    }
    return -1;  // compared every element
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/linear_search.hpp

References