fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. using namespace std;
  4.  
  5. const int A[] = {4, 2, 5, 3, 7, 4, 2, 6, 8, 4, 1, 10, 10, 10, 20, 11, 15, 13, 28, 99, 11 };
  6. const int B[] = {10, 99, 20, 30, 11, 100, 150, 101, 125};
  7. const int C[] = {10, 20, 30, 40, 5};
  8.  
  9. int find_pivot(const int a[], int n)
  10. {
  11. int lo = 0, hi = n-1;
  12. for (int i=1;i<n && lo<=hi; ++i)
  13. {
  14. // find the low-maximum that is no greater than our
  15. // current high-minimum.
  16. if (a[i] > a[lo] && a[hi] >= a[i])
  17. lo = i;
  18.  
  19. // likewise, find the hi-minimum that is not less than
  20. // our current low-maximum.
  21. if (a[(n-1)-i] <= a[hi] && a[lo] < a[(n-1)-i])
  22. hi = (n-1)-i;
  23. }
  24. return (lo == hi || a[lo] == a[hi] ? hi : -1);
  25. }
  26.  
  27. int main(int argc, char* argv[])
  28. {
  29. int n = find_pivot(A, sizeof(A)/sizeof(A[0]));
  30. if (n >=0)
  31. cout << "A[" << n << "] = " << A[n] << endl;
  32. else
  33. cout << "A has no viable pivot.";
  34.  
  35. n = find_pivot(B, sizeof(B)/sizeof(B[0]));
  36. if (n >=0)
  37. cout << "B[" << n << "] = " << B[n] << endl;
  38. else
  39. cout << "B has no viable pivot.";
  40.  
  41. n = find_pivot(C, sizeof(C)/sizeof(C[0]));
  42. if (n >=0)
  43. cout << "C[" << n << "] = " << C[n] << endl;
  44. else
  45. cout << "C has no viable pivot.";
  46.  
  47. return EXIT_SUCCESS;
  48. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
A[11] = 10
B[5] = 100
C has no viable pivot.