📘 Lesson · Lesson 57
Second Largest in Array
Second Largest in Array
Find Second Largest Element in an Array in Java
This finds the second largest number in an array in a single pass.
Java Program
int[] a = {10, 5, 20, 8, 15};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) { second = x; }
}
System.out.println("Second largest: " + second);
Output
Second largest: 15
How it Works
- Track the largest and second largest while looping once.
- When a new max is found, the old max becomes second.
Summary
- This finds the second largest number in an array in a single pass.
Find Second Largest Element in an Array in Java
यह array में दूसरी सबसे बड़ी संख्या एक ही pass में ढूंढता है।
Java Program
int[] a = {10, 5, 20, 8, 15};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) { second = x; }
}
System.out.println("Second largest: " + second);
Output
Second largest: 15
कैसे काम करता है
- एक बार loop करते हुए largest और second largest track करें।
- नया max मिले तो पुराना max second बन जाता है।
सारांश
- यह array में दूसरी सबसे बड़ी संख्या एक ही pass में ढूंढता है।