01 / 21

Binary Search
in C++

Learn how to efficiently search sorted data by repeatedly halving the search space: from the core concept to std::binary_search in the C++ Standard Library.

C++ Algorithms

What is Binary Search?

Binary search is an algorithm that finds the position of a target value within a sorted array. Instead of checking every element one by one, it eliminates half of the remaining elements at each step.

Precondition
The array must be sorted before binary search can work.
Goal
Find whether a target exists, and if so, where it is located.

Why Does Speed Matter?

Imagine searching for a name in a phonebook with 1,000,000 entries. A linear search checks up to all one million entries. Binary search needs at most 20 checks.

Array Size (n) Comparisons 100 1K 100K 1M 10 20
\( O(n) \)
\( O(\log n) \)

Key Vocabulary

low
Index of the first element in the current search range.
mid
Index of the middle element: \( \text{mid} = \lfloor(\text{low} + \text{high}) / 2\rfloor \).
high
Index of the last element in the current search range.

The Algorithm Step by Step

1
Set boundaries: \(\text{low} = 0\), \(\text{high} = n - 1\).
2
Compute mid: \(\text{mid} = \lfloor(\text{low} + \text{high}) / 2\rfloor\).
3
Compare: if \( \text{arr}[\text{mid}] == \text{target} \), return mid.
4
Narrow range: if \( \text{target} < \text{arr}[\text{mid}] \), set \(\text{high} = \text{mid} - 1\). Otherwise set \(\text{low} = \text{mid} + 1\).
5
Repeat steps 2-4 while \(\text{low} \leq \text{high}\). If the loop ends, the target is not found.

Visual Walkthrough

Search for target = 23 in the sorted array below.

Step 1: 2 7 11 15 23 34 51 low mid high
\( 23 > 15 \)
Step 2: 23 34 51 eliminated low mid high
\( 23 < 34 \)
Step 3: 23 eliminated eliminated ✓ Found! 7 elements searched in just 3 steps (Linear search would take up to 5 steps)

Writing It in C++

int binarySearch(int arr[], int n, int target) { int low = 0, high = n - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; // found else if (arr[mid] < target) low = mid + 1; // search right half else high = mid - 1; // search left half } return -1; // not found }

Linear vs Binary Search

Linear Search Binary Search
Time Complexity \( O(n) \) \( O(\log n) \)
Requires Sorting? No Yes
1M Elements (worst) 1,000,000 checks 20 checks
Implementation Simple loop Slightly more involved
Best For Small or unsorted data Large sorted data

How to Apply Binary Search

1
Confirm the data is sorted. If not, sort it first using std::sort (\( O(n \log n) \)).
2
Decide your question: Does the target exist? What index is it at? Where would it be inserted?
3
Choose your tool: Write your own loop, or use std::binary_search, std::lower_bound, or std::upper_bound.
4
Handle the "not found" case. Return \( -1 \) (manual) or check the returned iterator (STL).

Using std::binary_search

The C++ Standard Library provides std::binary_search in the <algorithm> header. It returns a simple bool: does the value exist in the sorted range?

#include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v = {2, 7, 11, 15, 23, 34, 51}; if (std::binary_search(v.begin(), v.end(), 23)) std::cout << "Found!"; else std::cout << "Not found."; }

lower_bound & upper_bound

std::lower_bound
Returns an iterator to the first element that is not less than the target (\( \ge \text{target} \)).
std::upper_bound
Returns an iterator to the first element that is greater than the target (\( > \text{target} \)).
auto it = std::lower_bound(v.begin(), v.end(), 23); if (it != v.end() && *it == 23) { int index = it - v.begin(); std::cout << "Found at index " << index; }

Example 1: Basic Search

Search for target = 11 in {3, 5, 8, 11, 14, 19}.

Pass 1: 3 5 8 11 14 19 mid=2
\( 11 > 8 \to \text{go right} \)
Pass 2: eliminated 11 14 19 mid=4
\( 11 < 14 \to \text{go left} \)
Pass 3: eliminated 11 eliminated ✓ Found at index 3

Example 2: Not Found

Search for target = 10 in {3, 5, 8, 11, 14, 19}.

Pass 1: 3 5 8 11 14 19 mid=2, val=8
\( 10 > 8 \to \text{right} \)
Pass 2: 11 14 19 mid=4, val=14
\( 10 < 14 \to \text{left} \)
Pass 3: 11 mid=3, val=11
\( 10 < 11 \to \text{left} \)
\( \text{low} > \text{high} \to \) Not Found (return -1)

Example 3: STL in Action

Given an unsorted vector, sort it and then use the STL to check membership and find position.

#include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v = {19, 3, 14, 8, 5, 11}; std::sort(v.begin(), v.end()); // {3,5,8,11,14,19} // Check existence bool found = std::binary_search(v.begin(), v.end(), 14); std::cout << found << "\n"; // 1 (true) // Find position auto it = std::lower_bound(v.begin(), v.end(), 14); std::cout << "Index: " << (it - v.begin()); // 4 }

Common Mistakes

✕ Unsorted Data
Using binary search on an array that hasn't been sorted. Results are unpredictable and wrong.
✕ Integer Overflow
Computing mid as \( (\text{low} + \text{high}) / 2 \). For large arrays, low + high can exceed \( 2^{31} - 1 \). Use \( \text{low} + (\text{high} - \text{low}) / 2 \).
✕ Off-by-One Errors
Using \( < \) instead of \( \le \) in the while condition, or forgetting \( \text{mid} + 1 \) / \( \text{mid} - 1 \) when narrowing. This causes infinite loops or missed elements.

STL Binary Search Cheat Sheet

Function Returns Use When
std::binary_search bool You only need yes/no
std::lower_bound iterator to \( \ge \) target You need the position
std::upper_bound iterator to \( > \) target You need the insertion point
std::equal_range pair of iterators You need all occurrences

Question 1 of 5

What is the most important precondition for binary search to work correctly?

Question 2 of 5

What is the time complexity of binary search on a sorted array of \( n \) elements?

Question 3 of 5

In C++, what does std::binary_search return?

Question 4 of 5

Why do we compute mid as low + (high - low) / 2 instead of (low + high) / 2?

Question 5 of 5

You have the sorted array {1, 4, 7, 10, 13, 16} and search for target = 7. How many comparisons does binary search make?