How to find second largest element in an array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to find second largest element in an array?

7th Dec 2021, 6:20 AM
Dhairya Jain
1 Answer
+ 5
Take the first 2 elements of the array setting the larger of the 2 to a max variable and the smaller to the second variable. Loop over the remaining elements, checking if the element is greater than max. If it is, set second to max and max to the element. Else if the element is greater than the sec and not equal to max, then set the element to second.
7th Dec 2021, 6:50 AM
ChaoticDawg
ChaoticDawg - avatar