From d22742ddeabc4f9197d300068b3faccd733d740f Mon Sep 17 00:00:00 2001 From: pravigya <77122170+pravigya@users.noreply.github.com> Date: Tue, 5 Oct 2021 04:21:29 +0530 Subject: [PATCH] Finding the Peak element in an array --- peak_element.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 peak_element.cpp diff --git a/peak_element.cpp b/peak_element.cpp new file mode 100644 index 0000000..b39c0ae --- /dev/null +++ b/peak_element.cpp @@ -0,0 +1,33 @@ +// Find a peak element. An array element is a peak if it is NOT smaller than its neighbours. +#include +using namespace std; + +// Find the peak element in the array +int findPeak(int arr[], int n) +{ + // first or last element is peak element + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + + // check for every other element + for (int i = 1; i < n - 1; i++) { + + // check if the neighbors are smaller + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} + +// Driver Code +int main() +{ + int arr[] = { 1, 3, 20, 4, 1, 0 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Index of a peak point is " + << findPeak(arr, n); + return 0; +} \ No newline at end of file