Sunday, 7 September 2014

Find Second Largest element in an array

Algorithm:

1. Initialize max to first element of array and secondMax as INT_MIN
2. Loop through all the elements.
   a. If the current element is greater than max, then update max
       and secondMax. 
   b. Else if the current element is greater than secondMax then update 
    secondMax
 Input    : Array of n elements
Output : Second Largest Element
 
Implementation 
#include <iostream>
#include<string>
#include <cmath>
using namespace std;
int SecondMax ( int *a,int n )
{
    int max=a[0],secondMax=INT_MIN;
    for ( int k=1; k<n; k++ )
    {
        if ( a[k]>max )
        {
            secondMax=max;
            max=a[k];

        }
        else
            if ( a[k]>secondMax&& a[k]<max )
            {
                secondMax=a[k];
            }
    }
    return secondMax;
}
int main()
{
    int n,*a;
    cin>>n;
    a=new int[n];

    for ( int i=0; i<n; i++ )
    {
        cin>>a[i];
    }
    if ( n<=2 )
    {
        cout<<" Enter valid Input";
    }
    else
    {
        if ( SecondMax ( a,n ) == INT_MIN )
        {
            cout<<"Second Max element does not exist";
        }
        else
        {
            cout<<SecondMax ( a,n );
        }
    }
    delete a;
    getchar();
} 
 
Please comment if you find anything incorrect. 

No comments:

Post a Comment