01 / 21

Linear Search
in C++

Learn to traverse arrays and vectors element by element to find a target value: the simplest and most fundamental search algorithm.

C++ Algorithms

What is Searching?

Searching is the process of locating a specific element within a data structure. Given an array of \( n \) elements, we want to determine whether a target value exists and, if so, where it is.

Input
An array (or vector) of \( n \) elements and a target value to find
Output
The index of the target if found, or \( -1 \) if not present

Meet Linear Search

Linear search (also called sequential search) is the most straightforward approach: start at the beginning and check each element one by one until you either find the target or exhaust the entire collection.

3 0 7 1 1 2 9 3 5 4 2 5 8 6 scan left to right Target = 5 found!

Why Linear Search Matters

Simple
Easy to understand, implement, and debug: great for beginners
No Sorting
Works on any array: sorted or unsorted, any data type
Foundation
Understanding it deeply prepares you for binary search, hash maps, and more

The Algorithm Formally

1
Initialize an index variable \( i = 0 \).
2
Compare the element at position \( i \) with the target.
3
If they match, return \( i \) (the index where the target lives).
4
Otherwise, increment \( i \) and repeat step 2.
5
If \( i \geq n \), the target is not present: return \( -1 \).

Time Complexity

Best Case
\( O(1) \): target is the very first element
Average Case
\( O(n/2) = O(n) \): target is somewhere in the middle on average
Worst Case
\( O(n) \): target is at the very end, or not present at all
Array size \( n \) Comparisons O(n) O(1)

Linear vs Binary Search

Linear Search Binary Search
Time Complexity \( O(n) \) \( O(\log n) \)
Requires Sorting? No Yes
Data Structure Array, vector, list Sorted array / vector
Implementation Very simple Moderate
Best For Small or unsorted data Large sorted datasets

How to Implement It

1
Declare the function with parameters: the array (or vector), its size \( n \), and the target value.
2
Write a for-loop from \( i = 0 \) to \( i < n \).
3
Inside the loop, compare arr[i] with the target using ==.
4
If equal, immediately return \( i \).
5
After the loop, return \( -1 \) to indicate "not found".

Code: Array Version

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;   // found at index i
        }
    }
    return -1;      // not found
}

Code: Vector Version

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

Example 1: Target Found

Array: {4, 2, 7, 1, 9, 3}, target = 9

4
\(i=0\)
\(4 \neq 9\)
2
\(i=1\)
\(2 \neq 9\)
7
\(i=2\)
\(7 \neq 9\)
1
\(i=3\)
\(1 \neq 9\)
9
\(i=4\)
\(9 = 9\) ✓
3 5 Return 4 (found after 5 comparisons)

Example 2: Target Not Found

Array: {4, 2, 7, 1, 9, 3}, target = 6

4 ✕ 2 ✕ 7 ✕ 1 ✕ 9 ✕ 3 ✕ Return -1 (all 6 elements checked, not found)

Complete Program

#include <iostream>
#include <vector>
using namespace std;

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

int main() {
    vector<int> nums = {10, 23, 45, 70, 11, 15};
    int result = linearSearch(nums, 70);
    if (result != -1)
        cout << "Found at index " << result;
    else
        cout << "Not found";
    return 0;
}

Searching for Strings

Linear search works on any data type that supports ==. Here is a version for strings:

int findName(const vector<string>& names,
             const string& target) {
    for (int i = 0; i < (int)names.size(); i++) {
        if (names[i] == target) return i;
    }
    return -1;
}

Common Mistakes

✕ Off-by-One Error
Using \( i \leq n \) instead of \( i < n \) causes an out-of-bounds access on the last iteration.
✕ Returning Too Early
Returning \( -1 \) inside the loop (on the first mismatch) instead of after the loop ends.
✕ Wrong Return Type
Returning true/false when the question asks for the index, or vice versa.

Summary at a Glance

Property Detail
Algorithm Type Sequential / Brute-Force
Best Case \( O(1) \)
Worst Case \( O(n) \)
Space Complexity \( O(1) \) (no extra memory)
Requires Sorting? No
Works With Arrays, vectors, lists, strings
"Not Found" Return \( -1 \)

Question 1 of 5

What is the worst-case time complexity of linear search on an array of \( n \) elements?

Question 2 of 5

Given arr = {5, 12, 8, 3, 20} and target = 8, what does linearSearch(arr, 5, 8) return?

Question 3 of 5

What value should a linear search function return when the target is not found in the array?

Question 4 of 5

What is wrong with this implementation?

Question 5 of 5

Which of the following is NOT an advantage of linear search over binary search?