Binary search in C++
Find a value in a sorted array in O(log n) steps. Press Run to try it, then change the code and run it again.
#include <bits/stdc++.h>
using namespace std;
int binarySearch(const vector<int> &a, int target) {
int lo = 0, hi = (int)a.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
int main() {
vector<int> a = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
cout << "23 is at index " << binarySearch(a, 23) << '\n';
cout << "40 is at index " << binarySearch(a, 40) << '\n';
// The standard library has it too:
cout << "lower_bound(40) points to " << *lower_bound(a.begin(), a.end(), 40) << '\n';
}
Output
Press Run to see the output.
More C++ examples
- Hello, World · The classic first C++ program.
- Vectors and sort · Read numbers into a vector, sort them and find the largest.
- Classes and objects · A class with a constructor, private data and member functions.
- Count words with a map · Use std::map to count how often each word appears.
- Competitive programming template · Fast input and output with bits/stdc++.h, ready for contest problems.