Searching
Binary Search (Iterative)
On a sorted array, narrow [lo, hi] window by halving until arr[mid]
equals the target or the window is empty. Demonstrates the
"discard half the search space" invariant.
Algorithm
Basic Implementation
basic.cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> arr = {1, 3, 5, 7, 9, 11, 13};
int target = 11;
int lo = 0;
int hi = static_cast<int>(arr.size()) - 1;
int result = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target) {
result = mid;
break;
}
if (arr[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
std::cout << result << std::endl;
return 0;
}
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- In C++, the input is a
std::vector<int>initialized as{1, 3, 5, 7, 9, 11, 13}and read by index; the vector is never mutated. - Search bounds are scalar
intvalues.histarts atstatic_cast<int>(arr.size()) - 1, and the loop continues whilelo <= hi. - The midpoint uses
lo + (hi - lo) / 2, avoiding directlo + hiaddition while still producing anintindex forarr[mid]. int result = -1is the not-found sentinel. On a match, the code writesresult = midand immediatelybreaks instead of continuing the search.- The trace records
lo=0, hi=6, mid=3witharr[mid]=7, then movesloto4; the next midpoint is5, wherearr[mid]=11setsresult=5. std::cout << result << std::endlwrites5. Visible allocation is the vector storage from the initializer list; mutation is limited to scalar search state.
midpoint
`mid = lo + (hi - lo) / 2` (overflow-safe integer division).
inclusive window
`hi` is inclusive. The loop runs while `lo <= hi`.