Skip to content

Searching: Linear & Binary

2 min read2 lessons in topic

Learning objective

By the end of this lesson you will be able to implement linear and binary search and explain when each is faster.

Finding an item in a collection is one of the most common operations in computing. Two classic approaches are linear and binary search.

Linear search

Check every item from the start until the value is found — or the list ends. Works on any list, sorted or not.

def linear_search(items, target):
    for i, item in enumerate(items):
        if item == target:
            return i
    return -1

print(linear_search([4, 9, 2, 7], 7))   # 3

Binary search

On a sorted list, compare the middle item: if the target is smaller, search the left half; if larger, search the right half. Each step halves the remaining items.

def binary_search(sorted_items, target):
    low, high = 0, len(sorted_items) - 1
    while low <= high:
        mid = (low + high) // 2
        if sorted_items[mid] == target:
            return mid
        elif sorted_items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([2, 5, 8, 12, 16], 12))   # 3

Which to use?

  • Linear search — O(n), works on any list
  • Binary search — O(log n), requires a sorted list
  • For one-off lookups in small lists, linear is perfectly fine

Code playground

Run and edit the starter code — experiment freely.

python · runnable

Output appears here when you press Run.

Practice exercise

Run binary search by hand on [3, 7, 9, 14, 21] looking for 14 — list the midpoints you check.

Check your understanding

1. What must be true for binary search to work?

2. Linear search on a list of n items has complexity:

Self-graded — answer then check below.