How to find second largest number in an array in Java?

arrays, java

Solution

Sorting the array simply to find an order statistics is too wasteful. You can find the second largest element by following an algorithm that resembles the one that you already have, with an additional variable representing the second largest number.

Currently, the next element could be larger than the max or equal to/smaller than the max, hence a single `if` is sufficient:

if (times[i] > maxValue) {
    maxValue = times[i];
}

With two variables to consider, the next element could be

- Greater than the max - the max becomes second largest, and the next element becomes the max

- Smaller than the max but greater than the second largest - the next element becomes second largest.

A special care must be taken about the initial state. Look at the first two items, and assign the larger one to the `max` and the smaller to the second largest; start looping at the element number three, if there is one.

Here is how you can code it:

if (times[i] > maxValue) {
    secondLargest = maxValue;
    maxValue = times[i];
} else if (times[i] > secondLargest) {
    secondLargest = times[i];
}

Problem

I'm just practicing some MIT java assignments. But, I'm not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13 ``` public class Marathon { public static void main(String[] arguments) { String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" }; int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 }; for (int i = 0; i < names.length; i++) { System.out.println(names[i] + ": " + times[i]); } System.out.println(); System.out.println("Largest Timing " + Largest(times)); System.out.println(); } public static int Largest(int[] times) { int maxValue = times[0]; for (int i = 1; i < times.length; i++) { if (times[i] > maxValue) { maxValue = times[i]; } } return maxValue; } } ```

Original source