Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- int ternarySearch(int l, int r, int x, int arr[]) {
- while (l <= r) {
- int mid1 = l + (r - l) / 3;
- int mid2 = r - (r - l) / 3;
- if (arr[mid1] == x) {
- return mid1;
- }
- if (arr[mid2] == x) {
- return mid2;
- }
- if (x < arr[mid1]) {
- r = mid1 - 1;
- } else if (x > arr[mid2]) {
- l = mid2 + 1;
- } else {
- l = mid1 + 1;
- r = mid2 - 1;
- }
- }
- return -1;
- }
- signed main() {
- int n, x;
- cin >> n >> x;
- int *arr = new int[n + 1];
- for (int i = 1; i <= n; i++) {
- cin >> arr[i];
- }
- sort(arr + 1, arr + n + 1);
- cout << ternarySearch(1, n, x, arr) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement