fork(2) download
  1. #include <stdio.h>
  2.  
  3. // Recusive function to find peak in the array
  4. int findPeakElement(int A[], int low, int high, int n)
  5. {
  6. // find mid element
  7. int mid = (low + high) / 2;
  8.  
  9. // check if mid element is greater than its neighbors
  10. if ((mid == 0 || A[mid - 1] <= A[mid]) &&
  11. (mid == n - 1 || A[mid + 1] <= A[mid]))
  12. return mid;
  13.  
  14. // If the left neighbor of mid is greater than the mid element,
  15. // then find the peak recursively in the left sub-array
  16. if (mid - 1 >= 0 && A[mid - 1] > A[mid])
  17. return findPeakElement(A, low, mid - 1, n);
  18.  
  19. // If the right neighbor of mid is greater than the mid element,
  20. // then find the peak recursively in the right sub-array
  21. return findPeakElement(A, mid + 1, high, n);
  22. }
  23.  
  24. // main function
  25. int main(void)
  26. {
  27. int A[] = { 8, 9, 10, 2, 5, 6 };
  28. int n = sizeof(A) / sizeof(A[0]);
  29.  
  30. int index = findPeakElement(A, 0, n - 1, n);
  31. printf("The peak element is %d", A[index]);
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
The peak element is 10