WAP to find the second largest number of an array
Objective
Write a C++ program to find the second largest element of an array.
Algorithm / Approach
- Find the absolute largest element (
max) and record its indexm. - Initialize the second largest
smaxto a different element. - Loop through the array again, skipping index
m. - If you find a number larger than
smax, update it:if(smax < a[i] && m != i). - Print the second largest element.
main.cpp
#include<iostream>
using namespace std;
int main() {
int m = 0, a[5],max,smax ;
cout<<"Enter 5 Elements : ";
for(int i =0; i< 5; i++) {
cin>>a[i];
}
max = a[0];
for(int i =1; i< 5; i++) {
if(a[i]>max) {
max = a[i];
m = i;
}
}
smax = a[5-m-1];
for(int i =0 ; i< 5; i++) {
if(smax< a[i] && m!= i) {
smax = a[i];
}
}
cout<<"Second Max = "<< smax;
return 0;
}
Expected Output
Enter 5 Elements : 1 3 45 32 54 Second Max = 45
Explanation of the Program
- Just like finding the second smallest, we identify the champion and then find the best of the remaining contenders by explicitly ignoring the champion's index.
- An alternative approach would be to sort the entire array in descending order and simply pick the second element, but sorting takes O(n log n) time, making this two-pass O(n) approach mathematically faster.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)