Walk an array once looking for a target value. Return the index of the first match, or -1 if none. The simplest possible search loop.

Algorithm

Canonical input arr = [4, 7, 1, 9, 3, 8] with target = 9 finishes after four compares; the matching index is 3.

early exit Return the index the moment `arr[i]` equals the target. Walking past it would defeat the point.
sentinel return A no-match walk falls off the loop and returns `-1`.

Basic Implementation

basic.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <vector>

int linearSearch(const std::vector<int>& arr, int target) {
    for (size_t i = 0; i < arr.size(); ++i) {
        if (arr[i] == target) {
            return static_cast<int>(i);
        }
    }
    return -1;
}

int main() {
    std::vector<int> arr = {4, 7, 1, 9, 3, 8};
    int target = 9;
    int result = linearSearch(arr, target);
    std::cout << result << std::endl;
    return 0;
}
  1. arr ← [4, 7, 1, 9, 3, 8]

    13int main() {14    std::vector<int> arr = {4, 7, 1, 9, 3, 8};15    int target = 9;
    values this step[4, 7, 1, 9, 3, 8]arr
  2. target ← 9

    14std::vector<int> arr = {4, 7, 1, 9, 3, 8};15int target = 9;16int result = linearSearch(arr, target);
    values this step9target[4, 7, 1, 9, 3, 8]arr
  3. result ← -1

    15int target = 9;16int result = linearSearch(arr, target);17std::cout << result << std::endl;
    values this step-1result9target
  4. match ← no

    5for (size_t i = 0; i < arr.size(); ++i) {6    if (arr[i] == target) {7        return static_cast<int>(i);
    values this stepnomatch0i4arr[i]9target
  5. match ← no

    5for (size_t i = 0; i < arr.size(); ++i) {6    if (arr[i] == target) {7        return static_cast<int>(i);
    values this stepnomatch1i7arr[i]9target
  6. match ← no

    5for (size_t i = 0; i < arr.size(); ++i) {6    if (arr[i] == target) {7        return static_cast<int>(i);
    values this stepnomatch2i1arr[i]9target
  7. match ← yes

    5for (size_t i = 0; i < arr.size(); ++i) {6    if (arr[i] == target) {7        return static_cast<int>(i);
    values this stepyesmatch3i9arr[i]9target
  8. result ← 3

    6if (arr[i] == target) {7    return static_cast<int>(i);8}
    values this step3result3i
  9. stdout ← 3

    16int result = linearSearch(arr, target);17std::cout << result << std::endl;18return 0;
    values this step3stdout3result

Complexity

  • Time: O(n)
  • Space: O(1)

Implementation notes

  • C++: explicit for (size_t i = 0; i < arr.size(); ++i). Never use std::find(arr.begin(), arr.end(), target) — the lesson is teaching the walk.
  • Function signature int linearSearch(const std::vector<int>& arr, int target) documents the integer-array contract; the static_cast<int>(i) makes the size/index sign discipline explicit.
  • The replay shows the running index, the element being checked, and a match indicator on each frame.