bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Second Largest Array Element

How To Find the Second Largest Element in an Array

Find the second highest number without sorting the whole array:

Example

int[] nums = {12, 5, 9, 21, 21, 7};
Integer first = null, second = null;
for (int n : nums) {
  if (first == null || n > first) {
    second = first;
    first = n;
  } else if ((second == null || n > second) && n != first) {
  second = n;
}
}
if (second != null) {
  System.out.println("Second largest: " + second);
} else {
System.out.println("No distinct second largest value.");
}

Previous

Java How To - Largest Element in an Array

Next

Java How To Find Min and Max in Array