smatskevich

BinSearch

Apr 17th, 2021
495
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×