Electronics & Telecommunication (University) is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Linear and binary search

Linear search scans each element one by one; binary search repeatedly halves a sorted array to locate a key — both are basic search algorithms with different preconditions and time/space costs.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Searching is a fundamental operation: engineers use search to find records, check membership, and locate values in arrays, databases, or in-memory data structures. Linear search is simple and works on any list; binary search is much faster but requires the list to be sorted — that trade-off (precondition vs speed) appears often in software and systems design.

Key ideas

  • Array: a collection of elements of the same type stored in contiguous memory locations and accessed by integer indices (usually 0-based in C/C++).

  • Search problem: given a collection (here an array) and a value called the key, determine whether the key is present and, if needed, return its position.

  • Comparison: an operation that checks whether an array element equals, is less than, or greater than the key. We normally count comparisons to measure search cost.

  • Time complexity: a way to express how the number of basic operations (here comparisons) grows with input size n.

  • Best-case / Worst-case / Average-case: the minimum, maximum, and expected number of comparisons across inputs of size n, respectively.

  • Linear search (sequential search):

    • Definition: Linear search checks array elements one by one from a start index until the key is found or array end is reached.
    • Preconditions: none (array need not be sorted). Works on arrays, linked lists, and any iterable collection.
    • Procedure (for an array A of length n, 0-based indices): start i = 0; while i < n: if A[i] == key return i; i++ ; if finished return NOT FOUND.
    • Correctness: the algorithm examines each element in order; if key exists at index k it will be checked when i = k, so it returns k; if not present it examines all n elements and reports not found. This is a simple loop invariant proof: before each iteration with index i, all indices < i have been checked and do not contain key.
  • Binary search:

    • Definition: Binary search finds the key in a sorted array by repeatedly splitting the search interval in half and discarding the half that cannot contain the key.
    • Preconditions: the array must be sorted in non-decreasing (ascending) order. If duplicates exist, binary search can be adapted to find first/last occurrence but base algorithm returns any matching index.
    • Procedure (iterative form on array A[0..n-1]): set low = 0, high = n-1. While low <= high: mid = floor((low + high)/2). If A[mid] == key return mid. Else if A[mid] < key set low = mid + 1 else set high = mid - 1. If loop ends return NOT FOUND.
    • Correctness: each comparison either finds the key or halves the remaining search interval. Use loop invariant: at the start of each iteration the key, if present, must lie in A[low..high]. Initially low = 0, high = n-1 so invariant holds. After the comparison, the invariant is maintained because one half is rejected. The interval size strictly decreases, so termination occurs.
  • Exact statement about number of comparisons (worst-case) for binary search:

    • For an array of n distinct elements, the worst-case number of element comparisons is floor(log2 n) + 1 using the usual mid = floor((low+high)/2) and inclusive bounds [low, high]. Proof: each comparison reduces the size of the searching interval to at most half (more precisely to floor(current_size/2)). After k comparisons, the interval size ≤ floor(n / 2^k). The search ends when interval size becomes 0, so require n / 2^k < 1 → 2^k > n → k > log2 n, therefore worst-case k = floor(log2 n) + 1.
    • State assumptions: comparisons counted are only element vs key comparisons. We assume integer arithmetic gives mid as floor((low+high)/2). Also assume n ≥ 1; for n = 0 the loop performs zero comparisons.
  • Relationship with other topics: searches are used with sorting (e.g., binary search requires sorted arrays — see topics Merge sort / Quick sort), with Binary Search Trees (BSTs) where search cost relates to tree height, and with hashing (alternative approach to searching offering average-case O(1) lookups).

  • Diagrams to draw in an exam:

    • Linear search: draw a row of boxes labelled A[0], A[1], ..., A[n-1]. Show an arrow scanning from left to right, stopping where A[k] == key, label comparisons at each checked box.
    • Binary search: draw the array boxes A[0..n-1], then on top draw brackets showing current interval [low, high]. Mark mid index with a vertical line. Show how interval becomes either left half [low..mid-1] or right half [mid+1..high] depending on compare. Repeat two steps to show halving.

Formulas

n = number of elements in the array (unitless) T_linear_best(n) = Θ(1) — best case (key at first position) T_linear_worst(n) = Θ(n) — worst case (key not present or at last position) T_linear_avg(n) = Θ(n) — average case assuming uniform random position or negative. More exactly: expected comparisons for a successful search = (n+1)/2; for an unsuccessful search = n. T_binary_best(n) = Θ(1) — best case (mid is key immediately) T_binary_worst(n) = Θ(log n) — worst case comparisons ~ ⌊log2 n⌋ + 1 (base-2 log) T_binary_avg(n) = Θ(log n) — average case for uniform key or random misses Space (extra memory): S_linear = Θ(1) iterative; S_binary_iter = Θ(1), S_binary_rec = Θ(log n) due to recursion stack.

Syntax to remember (C++ snippets): int A[n]; // declare array (n constant or use vector) for (int i = 0; i < n; ++i) { if (A[i] == key) ... } // linear search loop int low = 0, high = n - 1, mid; while (low <= high) { mid = (low + high) / 2; if (A[mid] == key) ... } // binary search loop Use std::vector<int> A; and std::sort(A.begin(), A.end()); if you must sort before binary search.

Worked examples

Example 1 — Linear search (C++):

#include <bits/stdc++.h>
using namespace std;
int linear_search(const vector<int>& A, int key) {
    for (int i = 0; i < (int)A.size(); ++i)
        if (A[i] == key) return i; // return first index where key found
    return -1; // not found
}
int main() {
    int n; if (!(cin >> n)) return 0;
    vector<int> A(n);
    for (int i = 0; i < n; ++i) cin >> A[i];
    int key; cin >> key;
    int pos = linear_search(A, key);
    if (pos >= 0) cout << "Found at index " << pos << '\n';
    else cout << "Not found" << '\n';
    return 0;
}

Sample input:

5
10 23 5 8 23
23

Exact output:

Found at index 1

(Explanation: first occurrence at index 1. If you want last occurrence, scan from right.)

Example 2 — Iterative binary search (C++):

#include <bits/stdc++.h>
using namespace std;
int binary_search_iter(const vector<int>& A, int key) {
    int low = 0, high = (int)A.size() - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2; // avoids overflow
        if (A[mid] == key) return mid;
        else if (A[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}
int main() {
    int n; if (!(cin >> n)) return 0;
    vector<int> A(n);
    for (int i = 0; i < n; ++i) cin >> A[i];
    int key; cin >> key;
    // assume input array is already sorted
    int pos = binary_search_iter(A, key);
    if (pos >= 0) cout << "Found at index " << pos << '\n';
    else cout << "Not found" << '\n';
    return 0;
}

Sample input:

10
2 5 8 12 16 23 38 56 72 91
23

Exact output:

Found at index 5

Example 3 — Step-by-step binary search (theory style): Array A = [2,5,8,12,16,23,38,56,72,91], n = 10. Search key = 23. Steps:

  1. low=0, high=9, mid=floor((0+9)/2)=4, A[4]=16. Compare 16 vs 23 → 16<23 → discard left half. New low=mid+1=5, high=9.
  2. low=5, high=9, mid=floor((5+9)/2)=7, A[7]=56. Compare 56 vs 23 → 56>23 → discard right half. New low=5, high=mid-1=6.
  3. low=5, high=6, mid=floor((5+6)/2)=5, A[5]=23. Compare 23 vs 23 → equal, return index 5. Comparisons performed = 3, which is ≤ floor(log2 10) + 1 = 4. Final answer: Found at index 5.

Common mistakes

  • Off-by-one errors: wrong loop condition (use while low <= high), wrong updates (low = mid, high = mid, instead of mid ± 1). This causes infinite loops or missing the target.
  • Computing mid as (low + high) / 2 without guarding overflow in other languages; use mid = low + (high - low) / 2. (In C++ with int and typical competitive sizes this rarely overflows but teach the safe form.)
  • Confusing index conventions (0-based vs 1-based) while describing algorithms or giving complexity formulas.
  • Forgetting to handle duplicates when the question asks for first/last occurrence.
  • Counting operations inconsistently (counting comparisons vs assignments); state clearly what you count when claiming Θ(...) results.

For your exam

Possible question types:

  • Definitions and short notes: define linear search and binary search, state preconditions and complexity.
  • Derivations: derive worst-case number of comparisons of binary search = floor(log2 n) + 1 with a short proof using halving argument.
  • Programs: write C/C++ code for linear or binary search (iterative or recursive). Include input/output format if asked.
  • Diagrams: draw array boxes and illustrate one or two iterations of each algorithm.
  • Comparative questions: when to use linear vs binary (trade-offs: pre-sorting cost vs repeated queries). Full-marks answer checklist:
  • Correct definitions with preconditions (sortedness for binary search).
  • Correct pseudocode or syntactically correct C/C++ program that compiles and handles edge cases (empty array, single element, not found).
  • Correct derivation/proof for complexities with assumptions stated (what is being counted).
  • If asked, diagram showing indices, mid and updated intervals, or example run showing comparisons.

Quick check

  1. What is the worst-case time complexity of linear search for an array of n elements?
  2. What precondition is required for binary search to work correctly?
  3. For n = 1,000,000 (10^6), approximately how many comparisons does binary search need in the worst case? (use base-2 log) Answers: 1) Θ(n). 2) The array must be sorted (non-decreasing order). 3) ⌊log2(10^6)⌋ + 1 ≈ 20 (since log2(10^6) ≈ 19.93), so 20 comparisons.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?