Binary Search in C++
Binary Search in C++
Binary search is an efficient algorithm for finding an item in a sorted list by repeatedly dividing the search interval in half. Learn how it works.
In depth
Binary search is a highly efficient algorithm for locating a specific item within a sorted collection. It significantly outperforms linear search, especially for large datasets, by drastically reducing the number of comparisons needed.
The Problem with Linear Search
Imagine searching for a name in a phonebook with a million entries. A linear search would involve checking each entry one by one until the target is found or the end is reached. In the worst case, this means checking every single item. This approach has a time complexity of O(n), meaning the number of steps grows proportionally with the number of items.
How Binary Search Works
Binary search requires the data to be sorted. Instead of checking items sequentially, it starts by examining the middle element of the collection. If the middle element is the target, the search is complete. If the target is smaller than the middle element, the algorithm can discard the entire upper half of the collection. Conversely, if the target is larger, the lower half is discarded. This process of halving the search space repeats until the target is found or the search space is exhausted.
Step-by-Step Example
Consider a sorted array `[2, 5, 8, 12, 16, 23, 38]` and a target of `23`.
1. Initial state: `low = 0`, `high = 6`. Middle index `(0 + 6) / 2 = 3`. Element at index 3 is `12`. 2. Since `23 > 12`, we discard the left half (indices 0-3). Update `low = 3 + 1 = 4`. 3. Next iteration: `low = 4`, `high = 6`. Middle index `(4 + 6) / 2 = 5`. Element at index 5 is `23`. 4. The target `23` is found at index 5.
function binary_search(sorted_array, target):
low = 0
high = length(sorted_array) - 1
while low <= high:
mid = low + (high - low) / 2 // Prevents overflow for large low/high
if sorted_array[mid] == target:
return mid
else if sorted_array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 // Target not foundUsing C++ Standard Library
For robust and optimized implementations, C++ provides `std::lower_bound` in the `<algorithm>` header. This function works on sorted ranges and returns an iterator to the first element that is not less than the specified value. If the value is present, it points to its first occurrence. If not, it points to where the value *would* be inserted to maintain sorted order.
#include <vector>
#include <algorithm>
#include <iostream>
// Example usage:
std::vector<int> v = {2, 5, 8, 12, 16, 23, 38};
auto it = std::lower_bound(v.begin(), v.end(), 23);
if (it != v.end() && *it == 23) {
std::cout << "Found 23 at index: " << std::distance(v.begin(), it) << std::endl;
} else {
std::cout << "23 not found." << std::endl;
}Performance Comparison
Binary search has a time complexity of O(log n). This logarithmic growth means that even for extremely large datasets, the number of steps required to find an item increases very slowly. For example, searching a million items takes at most about 20 steps (log base 2 of 1,000,000 is approximately 19.9), a dramatic improvement over the million steps a linear search might take.
Key Takeaways
- Binary search requires the input data to be sorted.
- It works by repeatedly dividing the search space in half.
- Its time complexity is O(log n), making it highly efficient for large datasets.
- The C++ Standard Library provides `std::lower_bound` for effective binary search on sorted ranges.
- Always consider sorting your data if frequent searches are needed.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →