+C++20
The C++20 version reads an ascending integer array by const reference without copying it. lowerBound returns the insertion boundary; indexOfSorted returns a matching index or -1. Its three output lines match the TypeScript version below.
#include <cstddef>
#include <iostream>
#include <vector>
std::size_t lowerBound(const std::vector<int>& values, int target) {
std::size_t lo = 0;
std::size_t hi = values.size();
// Values before lo are below target; values from hi onward are at least target.
while (lo < hi) {
const auto mid = lo + (hi - lo) / 2;
if (values[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
std::ptrdiff_t indexOfSorted(const std::vector<int>& values, int target) {
const auto index = lowerBound(values, target);
// The insertion boundary may be at the array end, so check the range first.
if (index == values.size() || values[index] != target) return -1;
return static_cast<std::ptrdiff_t>(index);
}
int main() {
const std::vector<int> values{1, 3, 3, 7, 9};
std::cout << lowerBound(values, 3) << '\n';
std::cout << lowerBound(values, 6) << '\n';
std::cout << indexOfSorted(values, 6) << '\n';
return 0;
}
1
3
-1
TypeScript