fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int ternarySearch(int arr[], int n, int x) {
  5. int left = 0, right = n - 1;
  6.  
  7. while (left <= right) {
  8. int mid1 = left + (right - left) / 3;
  9. int mid2 = right - (right - left) / 3;
  10.  
  11. if (arr[mid1] == x) return 1;
  12. if (arr[mid2] == x) return 1;
  13.  
  14. if (x < arr[mid1])
  15. right = mid1 - 1;
  16. else if (x > arr[mid2])
  17. left = mid2 + 1;
  18. else
  19. left = mid1 + 1, right = mid2 - 1;
  20. }
  21.  
  22. return -1;
  23. }
  24.  
  25. int main() {
  26. int n,target;
  27. cin >> n >> target;
  28. int a[n];
  29. for(int i = 0;i<n;i++){
  30. cin >> a[i];
  31. }
  32. int result = ternarySearch(a, n, target);
  33. if(result==1) cout << "FOUND";
  34. else cout << "NOT FOUND";
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 5288KB
stdin
6 5
1 2 3 4 5 6
stdout
FOUND