Menu
Coddy logo textTech

Binary Search

Last updated

Binary search finds a target value in a **sorted** array by repeatedly halving the search window. It compares the middle element with the target: a match ends the search; otherwise the half that cannot contain the target is discarded and the window shrinks to the other half. Each comparison eliminates half of the remaining elements, which is why it runs in O(log n) — searching a million sorted values takes at most about 20 comparisons.

The animation above shows the lo, mid and hi pointers and dims the eliminated half after every comparison. The one non-negotiable precondition: the array must already be sorted — on unsorted data you need linear search or a sort first (see merge sort). The same halving idea powers the binary search tree.

Time & space complexity

CaseComplexityNotes
Best caseO(1)The middle element is the target on the first comparison.
Average caseO(log n)Each comparison halves the remaining window.
Worst caseO(log n)The window shrinks to a single element before matching or missing.
SpaceO(1)Iterative version keeps only the lo, hi and mid indices.

Step by step

StepWhat happens
1Set lo to the first index and hi to the last index of the sorted array.
2Compute the middle index: mid = (lo + hi) // 2.
3If a[mid] equals the target, return mid — found.
4If a[mid] is **less** than the target, the target can only be in the right half: set lo = mid + 1.
5If a[mid] is **greater** than the target, search the left half: set hi = mid - 1.
6Repeat from step 2 while lo <= hi; if the window empties, the target is not in the array.

Worked example

Searching for 5 in [1, 2, 3, 5, 7, 8, 9]:

PassWindow (lo..hi)mida[mid]Action
1[1, 2, 3, 5, 7, 8, 9] (0..6)35a[3] = 5 — target found at index 3.

A miss, step by step

Searching for 4 in the same array shows how the window empties:

PassWindow (lo..hi)mida[mid]Action
10..6355 > 4 — search the left half, hi = 2.
20..2122 < 4 — search the right half, lo = 2.
32..2233 < 4lo becomes 3, window empties: not found.
Use it whenAvoid it when
The data is already sorted (or you search it many times)The data is unsorted and searched only once — sorting first costs O(n log n)
The collection supports fast random access (arrays)You only have sequential access (linked lists)
The dataset is large — O(log n) shines at scaleThe dataset is tiny — a simple scan is just as fast and simpler

Binary Search code

A clean, runnable Binary Search implementation in Python, JavaScript, Java, C++, C, Pseudocode. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Binary Search code in Python

Python
1def binary_search(a, target):2    lo, hi = 0, len(a) - 13    while lo <= hi:4        mid = (lo + hi) // 25        if a[mid] == target:6            return mid7        if a[mid] < target:8            lo = mid + 1  # search the right half9        else:10            hi = mid - 1  # search the left half11    return -112
13
14nums = [1, 2, 3, 5, 7, 8, 9]  # must be sorted15print("Index of 5:", binary_search(nums, 5))16print("Index of 4:", binary_search(nums, 4))
Run this code in the Python Playground

Binary Search FAQ

What is the time complexity of binary search?
O(log n) in the average and worst case, because every comparison halves the remaining search window, and O(1) in the best case when the first middle element is the target. The iterative version uses O(1) extra space.
Why does binary search require a sorted array?
The halving step relies on order: comparing the target with the middle element only tells you which half to discard if everything left of the middle is smaller and everything right of it is larger. On unsorted data that inference is invalid — use linear search instead, or sort first.
What is the difference between binary search and linear search?
Linear search scans elements one by one (O(n)) and works on any array; binary search halves a sorted array's search window (O(log n)) but requires sorted input. For a handful of items the difference is negligible — at scale binary search wins decisively.
How many comparisons does binary search need?
At most about log2(n) + 1: 10 comparisons cover 1,000 elements, 20 comparisons cover 1,000,000. That logarithmic growth is what makes it the default lookup on sorted data.
What is the classic overflow bug in binary search?
Computing the middle as (lo + hi) / 2 can overflow fixed-size integers when lo + hi exceeds the type's maximum. The safe form is mid = lo + (hi - lo) / 2. In Python this doesn't matter (arbitrary-precision integers), but in Java/C/C++ it's a real, famous bug.
Is binary search the same as a binary search tree?
They share the halving idea but differ in structure: binary search is an algorithm over a sorted array, while a binary search tree is a linked data structure that keeps its keys ordered so lookups descend left or right at each node.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED