C++ How To Find the Second Largest Element in an Array
Find the Second Largest Element in an Array
Keep track of both the largest and the second largest value while you loop through the array:
Example
int numbers[] = {45, 12, 85, 32, 89, 39};
int largest = INT_MIN;
int second = INT_MIN;
for (int num : numbers) {
if (num > largest) {
second = largest;
largest = num;
} else if (num > second && num != largest) {
second = num;
}
}
cout << "Second largest: " << second;
Explanation:INT_MIN (from the <climits> library) is the smallest possible int, so any number in the array is larger.
When a new largest number is found, the old largest becomes the second largest.
Otherwise, a number that is between the two becomes the new second largest.
Related Pages
C++ How To Find the Largest Element