Lesson 5 · Core algorithms

Searching Algorithms

Every search method buys speed with a condition on the data. Linear search needs nothing and costs O(n). Binary search needs sorted data. Hashing needs extra memory and gives up order. Search trees keep order. The data and the number of queries decide which one fits.

Searching Algorithms concept diagramFinding 53 among 15 values three ways. Linear search reads 11 cells from the left. Binary search on the sorted array reads 4 cells: 38, 58, 47, then 53. A hash table computes the slot and reads 1 cell.finding 53 among 15 values: shaded cells are the ones readlinear11 reads3712182127333842475358646974works on any order · O(n)binary4 reads3712182127333842475358646974needs sorted input · O(log n)1342hash1 read53needs a hash table · O(1) on averagehash(53) = slot 10what the data already guarantees decides which search you may use
1

Types of Searching Algorithms

Searching means finding where a value is, or proving it is not there. The searching algorithms that data structures courses teach fall into four types, and each one asks something different of the data.

Linear search asks nothing. Binary search asks for sorted data you can index into. Hashing asks for a hash function and spare memory. A search tree asks for keys that can be compared, kept in order as they change.

So the first question is not which is fastest but which ones the data allows. The second is how many searches will run, because sorting or building an index costs time up front and only pays off when it is reused.

The four types of searching algorithms
MethodSet-upOne searchNeedsRange queries
Linear searchNoneO(n)NothingScan everything
Binary searchSort: O(n log n)O(log n)Sorted arrayYes
Hash tableBuild: O(n)O(1) averageHash function, memoryNo
Balanced search treeBuild: O(n log n)O(log n)Comparable keysYes
  • Pick from what the data allows, then by how many searches will run
2

Linear Search

Look at each element from one end until the target turns up or the data runs out. A hit at position k costs k comparisons; a miss costs all n, because the only way to prove a value is absent is to look at everything. That is O(n).

It is the only option for unsorted data you search once, for linked lists, and for streams you cannot revisit. It is also often the fastest choice on small arrays, up to a few dozen elements, because a straight scan reads memory in order and has no hard-to-predict branches.

A sentinel version copies the target into an extra slot at the end, so the loop never has to check whether it has run out of elements: one test per step instead of two.

  • Works on any collection, in any order
  • Hit: up to n comparisons; miss: always n
3

Linear Search vs Binary Search

Binary search compares the target with the middle of a sorted range and throws away the half that cannot hold it. Each comparison halves the range, so about 20 comparisons cover a million elements and 30 cover a billion: O(log n).

The price is the precondition. The array must be sorted, and it must allow jumping straight to the middle, which rules out linked lists. Run it on unsorted data and it does not slow down; it gives wrong answers, because it discards halves that hold the target.

So linear search vs binary search comes down to how many searches there are. Sorting costs about n log₂ n comparisons. For a single search on unsorted data a scan is cheaper. Once the number of searches passes roughly log₂ n, sorting once and searching many times wins. Bounds, invariants and the classic off-by-one bugs are covered in the binary search lesson.

Key reference

Terms, operations, and practical uses

Search vocabulary

  • TargetThe value or condition being located.
  • Search intervalThe region that is still capable of containing the answer.
  • Monotonic predicateA yes/no condition that changes direction at most once across an ordered domain.

Binary-search boundaries

  • Lower boundThe first position whose value is at least the target.
  • Upper boundThe first position whose value is greater than the target.
  • MidpointThe inspected position that proves which portion can be discarded.

Choose the right search

  • Linear searchNeeds no preprocessing and works on unsorted data.
  • Binary searchHalves a sorted range each step for O(log n) lookup.
  • Hash lookupProvides expected constant-time membership by maintaining an auxiliary index.
  • Binary search treeKeeps keys ordered, so range queries and successors stay cheap.
  • Sorting firstOrdering once pays off when a collection is searched many times.
  • Answer-space searchBinary-searches possible results when feasibility changes monotonically.
Implementation

Code in Python, C++ and Java

def binary_search(values, target):
    left, right = 0, len(values) - 1
    while left <= right:
        middle = left + (right - left) // 2
        if values[middle] == target:
            return middle
        if values[middle] < target:
            left = middle + 1
        else:
            right = middle - 1
    return -1
print('index', binary_search([2, 5, 8, 12, 16, 21, 29], 16))
#include <iostream>
#include <vector>
using namespace std;

int binarySearch(const vector<int>& values, int target) {
    int left = 0, right = (int)values.size() - 1;
    while (left <= right) {
        int middle = left + (right - left) / 2;   // avoids overflow
        if (values[middle] == target) return middle;
        if (values[middle] < target) left = middle + 1;
        else right = middle - 1;
    }
    return -1;
}

int main() {
    vector<int> values = {2, 5, 8, 12, 16, 21, 29};
    cout << "index " << binarySearch(values, 16) << '\n';
}
class Main {
    static int binarySearch(int[] values, int target) {
        int left = 0, right = values.length - 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;   // avoids overflow
            if (values[middle] == target) return middle;
            if (values[middle] < target) left = middle + 1;
            else right = middle - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] values = {2, 5, 8, 12, 16, 21, 29};
        System.out.println("index " + binarySearch(values, 16));
    }
}
Watch it run

Step through it

Running on keys [29, 5, 16, 2, 21, 8, 12]; targets 16 and 17; range 8 to 16

linear search, target 16array029152163242158612methodlinearcomparisons3resultindex 229 ≠ 16, 5 ≠ 16, 16 = 16found at index 2 after 3 comparisons
Step 1

Linear search for 16: three looks

The keys arrive in no particular order, so nothing tells us where 16 might be. Linear search checks index 0 (29), index 1 (5), index 2 (16): found after 3 comparisons. It needed nothing from the data, not even sorting.

Outputindex 2
1 / 13
4

Hash Lookup

A hash table does not search at all in the usual sense. It computes where a key should be: hash the key, reduce it to a bucket number, look in that bucket. With a sensible load factor a bucket holds about one key, so a lookup is O(1) on average however many keys there are.

For "have I seen this before?" nothing is faster, which is why so many nested-loop O(n²) solutions become one O(n) pass with a set. See Two Sum and Contains Duplicate.

Two costs come with it. The worst case is O(n) when many keys land in one bucket, and an attacker who knows the hash function can force that; this is why Python randomises its string hashes on every run. And a hash table scatters keys on purpose, so it cannot answer "smallest key", "keys between 8 and 16" or "next key after 12" without looking at every entry.

  • O(1) average, O(n) worst case
  • Exact-match lookups only: no order, no ranges
5

Search Trees

A binary search tree keeps every key in order: smaller to the left, larger to the right. A search walks down from the root, one comparison per level. Balanced versions such as AVL and red-black trees keep the height near log₂ n, so every search, insert and delete is O(log n) guaranteed.

Order is what the tree is for. It answers range queries (go down to the lower bound, then walk in order), floor and ceiling (the nearest key below or above a value), smallest and largest, and sorted iteration. That is why both std::map and std::unordered_map, or TreeMap and HashMap, exist side by side.

Without balancing, a tree built from sorted input becomes a chain and a search costs O(n). On disk, B-trees put hundreds of keys in each node so a lookup reads only three or four blocks, which is why database indexes use them.

  • Balanced trees: O(log n) guaranteed, order kept
  • Range, floor, ceiling and sorted iteration come free
6

Choosing a Searching Algorithm

  1. One search over unsorted data: linear search
  2. A few dozen elements or fewer: linear search is often fastest anyway
  3. Data that never changes and is searched many times: sort once, then binary search
  4. Many exact-match lookups, with inserts and deletes: hash table
  5. Any question about order or ranges, with inserts and deletes: balanced search tree
  6. Data on disk: B-tree or B+ tree index

The number of searches decides whether set-up is worth paying for; the kind of question decides what to build.

Other array searches refine binary search for special cases: jump search checks every √n-th element and then scans, interpolation search guesses the position from the value and averages O(log log n) on evenly spread data, exponential search doubles a bound first when the size is unknown, and ternary search finds the peak of a function that rises then falls.

  • Count the searches before paying for set-up
  • Order questions need a sorted array or a tree; exact matches suit a hash table