Advertisement
smatskevich

BinSearch

Apr 17th, 2021
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. // Возвращает индекс элемента или -1, если элемента нет.
  4. int BinarySearch(const double* arr, int count, double element) {
  5.   int b = 0; // Все слева от b меньше element.
  6.   int e = count;
  7.   while (e > b) {
  8.     int m = (b + e) / 2;
  9.     if (arr[m] < element) {
  10.       b = m + 1;
  11.     } else {
  12.       e = m;
  13.     }
  14.   }
  15.   return (b < count && arr[b] == element) ? b : -1;
  16. }
  17.  
  18. int main() {
  19.   int n = 0;
  20.   std::cin >> n;
  21.  
  22.   double* arr = new double[n];
  23.   for (int i = 0; i < n; ++i) {
  24.     std::cin >> arr[i];
  25.   }
  26.   double k = .0;
  27.   std::cin >> k;
  28.  
  29.   std::cout << BinarySearch(arr, n, k);
  30.   delete[] arr;
  31.   return 0;
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement