Google+ Program For Find Peak Elements in a Array [How to] - CodieeHome
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
__

Finding Peak Elements in Array

Goal:How to find  Peak elements in Given Array.

Method-Used: Linear Search.

Explanation: 

                    Elements which are greater than both their neighbors in given array,known as "Peak elements".

For this we will search for elements which are greater than their neighbors using linear search  and when we find a match satisfying   this condition,we return those elements as output.For corner elements we only consider their one neighbor. 

Example:   Suppose Given array is  A={10,5,20,10,2}

            then peak elements in array are- 10 and 20.

Program:

 #include<iostream.h>

#include<conio.h>

void main()
 {
    int a[10],i,n,k=0;
    cout<<"\n\tHow many elements you want to enter\n";
    cout<<"\t";
    cin>>n;
    cout<<"\n\tEnter Elements:\n";
    for(i=0;i<n;i++)
    {
     cout<<"\t";
     cin>>a[i];
    }
    cout<<"\n\tPeak elements are:\n";
    for(i=0;i<n;i++)
     {
       if(i==0 && a[i]>a[i+1])
        {
        cout<<"\t";
        cout<<a[i];
        k++;
        }
       else if(i==(n-1) && a[i]>a[i-1])
        {
        cout<<"\t";
        cout<<a[i];
        k++;
        }
       else if(a[i]>a[i+1] && a[i]>a[i-1])
       {
        cout<<"\t";
        cout<<a[i];
        k++;
        }
        else if(k==0)
            cout<<"there is no peak element";
      }
      getch();

}

Output:


Complexity:

                 Above program has worst case Complexity O(n). We can do it also by divide and conquer method. But in the divide conquer approach we can obtain only one peak elements not all.


If you want to share more information about topic discussed above or find anything incorrect Please do comments.    

0 comments:

Post a Comment

 
Top