Advertisement
rudolf222222

Untitled

Nov 1st, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int BinSearch(const int* arr, int amount) {
  4.   int mid = 0, end = 0;
  5.   int begin = 0, mid_index = 0;
  6.   end = amount - 1;
  7.   while (end - begin >= 1) {
  8.     if (arr[begin] < arr[end]) {
  9.       return begin;
  10.     }
  11.     mid = arr[(begin + end) / 2];
  12.     mid_index = (begin + end) / 2;
  13.     if (mid_index == 0) {
  14.       return end;
  15.     }
  16.     if (mid < arr[mid_index - 1] && mid < arr[mid_index + 1]) {
  17.       return mid_index;
  18.     }
  19.     if (mid > arr[mid_index - 1] && mid > arr[mid_index + 1]) {
  20.       return mid_index + 1;
  21.     }
  22.     if (mid < arr[end] && mid_index > 0) {
  23.       end = mid_index - 1;
  24.     } else if (mid > arr[begin]) {
  25.       begin = mid_index + 1;
  26.     } else {
  27.       return 0;
  28.     }
  29.   }
  30.   return 0;
  31. }
  32. void FindShift() {
  33.   int amount = 0;
  34.   std::cin >> amount;
  35.   int* arr = new int[amount];
  36.   for (int i = 0; i < amount; i++) {
  37.     std::cin >> arr[i];
  38.   }
  39.   std::cout << BinSearch(arr, amount);
  40.   delete[] arr;
  41. }
  42. int main() {
  43.   FindShift();
  44.   return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement