RUN

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.

main.cpp

#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

Open the full C++ online compiler →