Advertisement
STANAANDREY

ternary search

Jun 8th, 2021
937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. int ternarySearch(int l, int r, int x, int arr[]) {
  5.     while (l <= r) {
  6.         int mid1 = l + (r - l) / 3;
  7.         int mid2 = r - (r - l) / 3;
  8.  
  9.         if (arr[mid1] == x) {
  10.             return mid1;
  11.         }
  12.         if (arr[mid2] == x) {
  13.             return mid2;
  14.         }
  15.  
  16.         if (x < arr[mid1]) {
  17.             r = mid1 - 1;
  18.         } else if (x > arr[mid2]) {
  19.             l = mid2 + 1;
  20.         } else {
  21.             l = mid1 + 1;
  22.             r = mid2 - 1;
  23.         }
  24.     }
  25.     return -1;
  26. }
  27.  
  28. signed main() {
  29.     int n, x;
  30.     cin >> n >> x;
  31.     int *arr = new int[n + 1];
  32.     for (int i = 1; i <= n; i++) {
  33.         cin >> arr[i];
  34.     }
  35.     sort(arr + 1, arr + n + 1);
  36.     cout << ternarySearch(1, n, x, arr) << endl;
  37.     return 0;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement