Question:
Find a peak element
An array element is a peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor.
For Example:
#include<iostream>
using namespace std;
int PeakElement(int arr[], int n)
{
if (n == 1)
return arr[0];
if (arr[0] >= arr[1])
return 0;
if (arr[n - 1] >= arr[n - 2])
return n - 1;
for (int i = 1; i < n - 1; i++) {
if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1])
return i;
}
}
int main()
{
int arr[] = {6, 9, 20, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Index of a peak point is \n"<< PeakElement(arr, n);
return 0;
}
---------End---------