templates/binary-search-on-number.cpp
compilable
$cat templates/binary-search-on-number
Binary Search
Classic binary search for finding a target value in a sorted array in O(log n).
#binary-search#sorted-array#search
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
#include <bits/stdc++.h>
using namespace std;
int binarySearch(vector<int>& a, int target) {
int l = 0, r = (int)a.size() - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (a[m] == target) return m;
if (a[m] < target) l = m + 1;
else r = m - 1;
}
return -1;
}13 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Binary Search
Finds a target value in a sorted array by repeatedly halving the search interval.
How It Works
Overflow Safety
Midpoint computed as instead of to avoid integer overflow.