Sunday, 3 June 2018

C++ Program to find all the Peak Elements in Array

In this program an array is given to you and you have to find the peak elements in the array..  A peak element in the array is the element which is greater than its left and right elements.  Therefore, There can be multiple peak elements in the array. C++ Program to find all the peak elements in the array is given below.

For first and last element of the array we will check for the right and left elements respectively.


Example: Let arr={34,23,67,35,98}
Here peak elements are :  34, 67,98


PROGRAM:

#include <bits/stdc++.h>
using namespace std;

vector<int> find_peak(int arr[], int n)
{
   
     /* Declaring a vector to store the peak elements */
     std::vector<int> vect;

     /*Checking if first element of array is peak or not */
     if(arr[0]>arr[1]) vect.push_back(arr[0]);


     //checking rest of the elements

     for(int i=1;i<n-1;i++){
         if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){
             vect.push_back(arr[i]);
         }
     }
   

      /*Checking if last element of array is peak or not */
      if(arr[n-1]>arr[n-2]) vect.push_back(arr[n-1]);
      return vect;

}
int main(){
   
    int n;
 
    cout<<"\nEnter the number of elements:\n";
    cin>>n;

    int arr[n];

    cout<<"\nEnter the elements: \n\n";
    for(int i=0;i<n;i++){
        cin>>arr[i];
    } 

    vector<int> result=find_peak(arr,n);

    cout<<"\nThe peak elements in the array are: \n";
    for(int i=0;i<result.size();i++){
         cout<<result[i]<<" ";
    }

    return 0;

}


OUTPUT:







2 comments

You have a bug in your code. In your loop, the break condition should be 'i < n-2'

Can you give me the example using a Sample case..I don't think that's wrong...It should be i<=n-2 or i<n-1...


EmoticonEmoticon