Advertisement
_takumi

bs

Oct 15th, 2023 (edited)
664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <vector>
  5. #include <ctime>
  6. using namespace std;
  7.  
  8. int bs(const vector<int> &arr, int size, int x) {
  9.     int low = 0, high = size - 1, mid;
  10.     while (high >= low) {
  11.         mid = low + (high - low) / 2;
  12.         if (arr[mid] == x) {
  13.             return mid;
  14.         } else if (arr[mid] > x) {
  15.             high = mid - 1;
  16.         } else {
  17.             low = mid + 1;
  18.         }
  19.  
  20.     }
  21.     return -1;
  22. }
  23.  
  24. int main() {
  25.     srand(time(nullptr));
  26.     vector<int> arr(20);
  27.     for (int i = 0; i < 20; ++i) {
  28.         arr[i] = rand() % 100 + 1;
  29.     }
  30.     sort(begin(arr), end(arr));
  31.     for (int i = 0; i < 20; ++i) {
  32.         cout << arr[i] << " ";
  33.     }
  34.     cout << endl;
  35.     cout << bs(arr, 20, 50);
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement