Find a peak element in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the peak element in the given array

The peak element is an element that is greater than the surrounding elements. Let's see the steps to solve the problem.

  • Initialize the array with dummy data.

  • Check for the first element and last element for the peak element condition.

  • Iterate over the array from the second element.

    • Check whether the current element is greater than the previous element and the next element.

    • Return if the above condition satisfies.

  • Print the result

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findPeakElement(int arr[], int n) {
   if (n == 1) {
      return arr[0];
   }
   if (arr[0] >= arr[1]) {
      return arr[0];
   }
   if (arr[n - 1] >= arr[n - 2]) {
      return arr[n - 1];
   }
   for (int i = 1; i < n - 1; i++) {
      if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) {
         return arr[i];
      }
   }
   return arr[0];
}
int main() {
   int arr[] = { 1, 2, 5, 4, 7 };
   cout << findPeakElement(arr, 5) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

7

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Feb-2021 12:03:19
Advertisements