1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <vector>
#include <iostream>
#include <iomanip>
bool found1(const std::vector<int>& v, int trgt, size_t left, size_t right) {
if (left > right)
return false;
const auto i { left + (right - left) / 2 };
if (v[i] == trgt)
return true;
if (v[i] > trgt)
return found1(v, trgt, left, i - 1);
return found1(v, trgt, i + 1, right);
}
bool found(const std::vector<int>& v, int trgt) {
if (v.empty() || trgt < v.front() || trgt > v.back())
return false;
return found1(v, trgt, 0, v.size() - 1);
}
int main() {
const std::vector list { 3, 6, 8, 10, 12, 23, 78 };
std::cout << "3 " << std::boolalpha << found(list, 3) << '\n';
std::cout << "10 " << std::boolalpha << found(list, 10) << '\n';
std::cout << "78 " << std::boolalpha << found(list, 78) << '\n';
std::cout << "66 " << std::boolalpha << found(list, 66) << '\n';
std::cout << "1 " << std::boolalpha << found(list, 1) << '\n';
std::cout << "99 " << std::boolalpha << found(list, 99) << '\n';
}
|