Objective: Given an array of integers. find the second largest element in the array.
Example:
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 }; Second largest Element : 44
Approach:
- Keep track of largest element and when ever you change the value of largest element, store its current value to another variable, call it as second largest element.
- If you are not updating the largest element then check if second largest element is less than the current element, if yes then update it.
Complete Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SecondLargestElement { | |
public static int findSecond(int[] A) { | |
int fstNo = A[0]; | |
int sndNo = –1; | |
for (int i = 1; i < A.length; i++) { | |
if (fstNo < A[i]) { | |
sndNo = fstNo;// store the first largest no value to second | |
// largest | |
fstNo = A[i]; | |
} else if (sndNo < A[i]) { | |
sndNo = A[i]; | |
} | |
} | |
return sndNo; | |
} | |
public static void main(String[] args) { | |
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 }; | |
System.out.println("Second largest Element : " + findSecond(A)); | |
} | |
} |
Second largest Element : 44
Please find an optimized solution:
“http://quickinfobox.blogspot.in/2016/03/an-optimised-approach-to-find-second.html”