awsmpshk

Бинарный поиск (нерекурсивно)

May 24th, 2020
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.51 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int* createMas(int n)
  6. {
  7.     int* mas = new int[n];
  8.     for (int i = 0; i < n; ++i) cin >> mas[i];
  9.     return mas;
  10. }
  11.  
  12. int main()
  13. {
  14.     int n;
  15.     cin >> n;
  16.     int* mas = createMas(n);
  17.     int l = 0;
  18.     int r = n - 1;
  19.     int value;
  20.     cin >> value;
  21.     while (l < r)
  22.     {
  23.         int mid = (l + r) / 2;
  24.         if (value < mas[mid]) r = mid + 1;
  25.         else if (value > mas[mid]) l = mid;
  26.         else if (value == mas[mid])
  27.         {
  28.             cout << mid << endl;
  29.             break;
  30.         }
  31.     }
  32.     delete[] mas;
  33.     return 0;
  34. }
Add Comment
Please, Sign In to add comment