Quick Answer

Binary search finds a value in a sorted list. It checks the middle item. Then it drops the half that cannot contain the value. Ten items need 4 checks at most. A million items need 20. The list must be sorted first. Python and C++ code below was executed.

Binary search is the standard way to find a value in sorted data. It skips most items and halves the range with every check.

Think of a dictionary lookup. You open the middle and see whether your word comes before or after that page. Then you drop the other half of the book.

Trace, tested code, timings and the middle index bug follow below.

What Is Binary Search?

This method compares your value with the middle item of a sorted list. Equal items end the search. Smaller middle items send you to the right half and larger ones send you to the left half.

Sorted order is the rule that makes this work. Without it the discarded half could still contain your value. Lists in this guide are arrays and arrays give direct access to the middle item.

Full reference sits in the binary search lesson.

Which 2 Approaches Find a Value in a Sorted List?

Table below lists both approaches with their cost in the worst case.

ApproachTimeNeeds sorted data
Approach #1 Linear scan (brute force)O(n)No
Approach #2 Halving the range (fewest checks)O(log n)Yes

Approach #1: Linear Scan (Brute Force)

What you get. You get a method that works on any list. Check items one by one from the start. Details sit in the guide to linear search.

Approach #2: Halve the Range (Fewest Checks)

What you get. Far fewer checks on large sorted lists. Track a low and a high index. Check the middle and move one index past it.

How Does Binary Search Work Step by Step?

Take the sorted list 2, 5, 8, 12, 16, 23, 38, 45, 56 and 72. You search for 23. Indexes go from 0 to 9.

Table below traces the 3 checks. Trace output came from the Python function in the next section.

CheckLowHighMidValue at midAction
10941616 is below 23 so move low to 5
25974545 is above 23 so move high to 6
356523Match found at index 5

Watch the range shrink on the binary search visualiser. Another page, the lower bound visualiser, shows the variant that finds the first matching position.

How Do You Code Binary Search in Python and C++?

Python version below has both approaches so you can compare them. Binary search returns the index or -1 for a missing value.

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


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

C++ version below uses the same loop. It builds the middle index in the safe form explained in the next section.

#include <iostream>
#include <vector>

int binarySearch(const std::vector<int>& items, int target) {
    int low = 0;
    int high = static_cast<int>(items.size()) - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (items[mid] == target) return mid;
        if (items[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main() {
    std::vector<int> items = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72};
    std::cout << binarySearch(items, 23) << " " << binarySearch(items, 7) << "\n";
    return 0;
}

Tested. Python 3.13.18 passed checks for the first item, the last item, a missing value, an empty list, a single item list and 2,000 random lists compared with linear search. g++ 13.3 compiled the C++ sample with warnings on and printed 5 -1. Tests ran in a cloud sandbox.

Why Is the Middle Index Formula a Bug Risk?

Many versions compute the middle as low plus high divided by 2. Sum of two large indexes can exceed the largest integer. Joshua Bloch described this bug in a 2006 Google Research post and it affected the binary search in the Java library at that time.

Example with 32 bit integers. Low is 1,500,000,000 and high is 2,000,000,000. Their sum is 3,500,000,000 and the largest 32 bit value is 2,147,483,647.

Safe form is low plus (high minus low) divided by 2. That form gives 1,750,000,000 for the same values. Python integers do not overflow but the safe form costs nothing and builds a good habit.

What Is the Time Complexity of Binary Search?

Best case is O(1) when the first middle item matches. Worst case is O(log n) because every check halves the range. Space is O(1) for the loop version.

Maximum number of checks equals the floor of log base 2 of n plus 1. Test results confirmed 4 checks at most for 10 items and 5 for 16 items.

List sizeMaximum checks
104
165
1,00010
1,000,00020

Values for 1,000,000 come from the formula and values for 1,000 and below were counted by test.

Which Is Better in Binary Search vs Linear Search?

Large sorted lists favour the halving method. One test searched for the last value in a list of 1,000,000 sorted integers with the best of 5 trials in CPython 3.13.18.

MethodTime to find the last value
Linear search0.0239 s
Binary search0.0000018 s

Sorting costs time too. Unsorted data gives wrong answers.

For one lookup in an unsorted list a plain scan is cheaper than sorting first. For many lookups sort once and then search.

Next steps sit in the DSA roadmap and the binary search practice set.

Frequently Asked Questions

What Is the Worst Case Time Cost?

It is O(log n) in the worst case. Every check halves the remaining range.

Must the List Be Sorted First?

Yes. Without sorted order the discarded half could still contain the value and the result is wrong.

What Happens When the Value Is Missing?

It returns a signal chosen by the code. Samples above return -1.

Why Does Halving Beat Linear Search?

Linear search checks items one by one. Halving drops half of the range with every check.

Can the Loop Be Written With Recursion?

Yes. Recursive code calls the function again on the left or right half. Loop code above uses less memory.

What Is the Safe Way to Calculate the Middle Index?

Use low plus (high minus low) divided by 2. It avoids overflow for large indexes.

How Many Checks Do 1,000,000 Items Need?

At most 20 checks. That value comes from the floor of log base 2 of 1,000,000 plus 1.

What Should You Remember About Binary Search?

Sort the data first. Then halve the range until the value appears or the range is empty.

Key takeaways.

  • Binary search vs linear search favours halving on sorted data.
  • Sorted data and O(log n) cost define the method.
  • One million items need 20 checks at most.
  • Use the safe middle index formula in every language.

Check yourself. Sixteen sorted items need 5 checks at most.