C Program to find second largest element of an array.
Objective
Write a C program to find the second largest element of an array.
Algorithm / Approach
- Read an array of size
n. - Find the absolute largest element (
max) and record its indexj. - Initialize the second largest
smaxto an element at the opposite end of the array. - Loop through the array again to find the maximum value, but skip the index
jusing the conditionj != i. - Print the second largest element.
main.c
#include<stdio.h>
int main() {
int a[50],n,i,j=0,max,smax;
printf("Enter Array Size: ");
scanf("%d",&n);
printf("Enter %d element: ",n);
for(i=0;i< n;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=1;i< n;i++) {
if(max < a[i]) {
max=a[i];
j = i;
}
}
smax=a[n-j-1];
for(i=1;i< n;i++) {
if(smax < a[i] && j != i)
smax = a[i];
}
printf("2nd Largest: %d",smax);
return 0;
}
Expected Output
Enter Array Size: 5 Enter 5 element: 1 2 3 4 5 2nd Largest: 4
Explanation of the Program
- Just like finding the second smallest, we do this in two phases: find the champion, and then find the best of the remaining contenders by explicitly ignoring the champion's index.
- An alternative approach is to sort the entire array in descending order and simply pick the element at index 1, 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)