Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <random>
- #include <cmath>
- #include <iomanip>
- #include <algorithm>
- using namespace std;
- void show(const vector<int>& box) {
- if (box.empty()) puts("Empty box!");
- else {
- const auto width = static_cast<streamsize>(log10(box.back())) + 2;
- auto n = 0;
- for (auto x : box) {
- cout << setw(width) << x;
- if (0 == ++n % 10) puts("");
- }
- puts("");
- }
- }
- vector<int> make_random_array(const size_t length) {
- uniform_int_distribution<> uid(1, static_cast<int>(length << 1));
- mt19937 gen{ random_device()() };
- auto rand = [&](int& x) { x = uid(gen); };
- vector<int> box(length);
- for (auto& x : box) x = uid(gen);
- puts("Create and view an array");
- show(box);
- sort(box.begin(), box.end());
- puts("View the sorted array");
- show(box);
- return box;
- }
- // Алгоритм бинарного поиска
- auto bin_search(const int key, vector<int>& box) {
- auto low = box.begin();
- auto high = box.end() - 1;
- while (low <= high) {
- auto pos = distance(low, high) >> 1;
- auto mid = low + pos;
- if (*mid < key) low = mid + 1;
- else if (*mid > key) high = mid - 1;
- else return mid;
- }
- return box.end();
- }
- int main() {
- cout << "Length: ";
- size_t length;
- cin >> length;
- auto box = make_random_array(length);
- auto pos = box.end();
- while (true) {
- cout << "Enter some number: ";
- int key;
- cin >> key;
- pos = bin_search(key, box);
- if (pos != box.end()) {
- const auto index = distance(box.begin(), pos);
- cout << "The specified number is in cells with an index: " << index << '\n';
- } else {
- puts("Number not found!");
- }
- }
- }
Add Comment
Please, Sign In to add comment