NickAndNick

Алгоритм бинарного поиска

Jun 22nd, 2022 (edited)
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <random>
  4. #include <cmath>
  5. #include <iomanip>
  6. #include <algorithm>
  7. using namespace std;
  8. void show(const vector<int>& box) {
  9.     if (box.empty()) puts("Empty box!");
  10.     else {
  11.         const auto width = static_cast<streamsize>(log10(box.back())) + 2;
  12.         auto n = 0;
  13.         for (auto x : box) {
  14.             cout << setw(width) << x;
  15.             if (0 == ++n % 10) puts("");
  16.         }
  17.         puts("");
  18.     }
  19. }
  20. vector<int> make_random_array(const size_t length) {
  21.     uniform_int_distribution<> uid(1, static_cast<int>(length << 1));
  22.     mt19937 gen{ random_device()() };
  23.     auto rand = [&](int& x) { x = uid(gen); };
  24.     vector<int> box(length);
  25.     for (auto& x : box) x = uid(gen);
  26.     puts("Create and view an array");
  27.     show(box);
  28.     sort(box.begin(), box.end());
  29.     puts("View the sorted array");
  30.     show(box);
  31.     return box;
  32. }
  33. // Алгоритм бинарного поиска
  34. auto bin_search(const int key, vector<int>& box) {
  35.     auto low = box.begin();
  36.     auto high = box.end() - 1;
  37.     while (low <= high) {
  38.         auto pos = distance(low, high) >> 1;
  39.         auto mid = low + pos;
  40.         if (*mid < key) low = mid + 1;
  41.         else if (*mid > key) high = mid - 1;
  42.         else return mid;
  43.     }
  44.     return box.end();
  45. }
  46. int main() {
  47.     cout << "Length: ";
  48.     size_t length;
  49.     cin >> length;
  50.     auto box = make_random_array(length);
  51.     auto pos = box.end();
  52.     while (true) {
  53.         cout << "Enter some number: ";
  54.         int key;
  55.         cin >> key;
  56.         pos = bin_search(key, box);
  57.         if (pos != box.end()) {
  58.             const auto index = distance(box.begin(), pos);
  59.             cout << "The specified number is in cells with an index: " << index << '\n';
  60.         } else {
  61.            puts("Number not found!");
  62.         }
  63.     }
  64. }
Add Comment
Please, Sign In to add comment