It can be done in O(N) time where 'N' is the size of array .
First , we find the largest element of the array in one traversal , store the largest number's index . Say it is "x".
In the second traversal , we , again find the largest element , but ignore the element at position "x" .
This way , we get the second largest element of the array .
Code :
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n ;
cin>>n ;
int a[n] ;
int i = 0 ;
while(i<n)
{
cin>>a[i];
i++;
}
int max = -10000000;
i=0;int x ;
while(i<n)
{
if(a[i]>max)
{
max = a[i] ;
x = i ;
}
i++;
}
max = -10000000;
i=0;
while(i<n)
{
if(a[i]>max && i!=x)
{
max = a[i] ;
}
i++;
}
cout<<max ;
return 0;
}