Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
Basic Implementation
basic.cpp
#include <iostream>
#include <unordered_map>
#include <vector>
int search(const std::vector<int>& arr, int target, int lo, int hi) {
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) return search(arr, target, mid + 1, hi);
return search(arr, target, lo, mid - 1);
}
int main() {
std::vector<int> arr{1, 3, 5, 7, 9, 11, 13};
int target = 11;
std::cout << search(arr, target, 0, static_cast<int>(arr.size()) - 1) << "\n";
return 0;
}
Complexity
- Time: O(log n)
- Space: O(log n) call stack
Implementation notes
- In C++, the input is a
std::vector<int>initialized as{1, 3, 5, 7, 9, 11, 13}and passed tosearch(const std::vector<int>& arr, int target, int lo, int hi)by const reference, so recursive calls do not copy or mutate the vector. - Bounds are scalar
intvalues. The initialhiisstatic_cast<int>(arr.size()) - 1, and the base case returns-1whenlo > hi. - The midpoint uses
lo + (hi - lo) / 2, producing anintindex forarr[mid]without directlo + hiaddition. - Recursive branch returns propagate directly: values below the target call
search(arr, target, mid + 1, hi), values above callsearch(arr, target, lo, mid - 1), and a match returnsmid. - The trace records the first call
(lo=0, hi=6),mid=3with value7and next call(4, 6), thenmid=5with value11returning result5. std::cout << search(...) << "\n"writes5. Visible allocation is the vector storage from the initializer list; runtime state is scalar call-frame data on the recursion stack.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison
This C++ DSA version keeps the same data and final output as every other DSA book in this wave.