fork(1) download
  1. #include <stdio.h>
  2.  
  3. // Ternary search algorithm to return the position of
  4. // target x in the array A of size N
  5. int TernarySearch(int arr[], int n, int x)
  6. {
  7. int low = 0, high = n - 1;
  8.  
  9. while (low <= high)
  10. {
  11. int left_mid = low + (high - low) / 3;
  12. int right_mid = high - (high - low) / 3;
  13.  
  14. // int left_mid = (2*low + high)/3;
  15. // int right_mid = (low + 2*high)/3;
  16.  
  17. if (arr[left_mid] == x)
  18. return left_mid;
  19.  
  20. else if (arr[right_mid] == x)
  21. return right_mid;
  22.  
  23. else if (arr[left_mid] > x)
  24. high = left_mid - 1;
  25.  
  26. else if (arr[right_mid] < x)
  27. low = right_mid + 1;
  28.  
  29. else
  30. low = left_mid + 1, high = right_mid - 1;
  31. }
  32.  
  33. return -1;
  34. }
  35.  
  36. // Ternary Search vs Binary search
  37. int main(void)
  38. {
  39. int A[] = { 2, 5, 6, 8, 9, 10 };
  40. int target = 6;
  41.  
  42. int n = sizeof(A) / sizeof(A[0]);
  43. int index = TernarySearch(A, n, target);
  44.  
  45. if (index != -1)
  46. printf("Element found at index %d", index);
  47. else
  48. printf("Element not found in the array");
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
Element found at index 2