Java Program to find the second largest element of an array .
Objective
Write a Java program to find the second largest element of an array.
Algorithm / Approach
- Initialize a hardcoded array.
- First Pass: Loop through the array to find the maximum element (
max) and store its index (m). - Initialize
smaxwith an element from a different index. - Second Pass: Loop through the array to find the maximum element again, but ignore the index
mby checkingm != i. - Update
smaxwhenever a larger valid element is found. - Print
smax.
Test.java
class Test {
void max() {
int[] a = new int[]{2,3,4,5,6};
int max = a[0], m = 0;
for(int i =1; i< a.length; i++) {
if(a[i]>max) {
max = a[i];
m = i;
}
}
int smax = a[a.length-m-1];
for(int i =0 ; i< a.length; i++) {
if(smax< a[i] && m!= i) {
smax = a[i];
}
}
System.out.print("2nd Max = "+smax);
}
public static void main(String[] a)
{
Test t = new Test();
t.max();
}
}
Expected Output
2nd Max = 5
Explanation of the Program
- This logic mirrors the second-smallest element problem.
- By keeping track of the index of the largest element, we can effectively "mask" it out during our second scan.
- The second scan then naturally finds the largest element out of the remaining numbers, which is by definition the second largest overall.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)
Common Mistakes
- Initializing the second max with 0 instead of a valid array element. If all array elements are negative numbers, 0 will incorrectly remain the maximum.