-4

I am doing a java project where I have to find the top two values of the times of a marathon. I have created arrays but I need to find the top two numbers in the array. Can I use the Math.max operator in Java. Here is the code btw :

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]);
        }
    }
}
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97

3 Answers3

2

You'll be better of creating a class for your results that contain a name and time. Have that class implement Comparable, then just use Collections.sort() and take the first two elements.

Something like this:

class RaceResult implements Comparable 
{
    final int time;
    final String name;

    RaceResult(String name, int time)
    {
        this.time = time;
        this.name = name;
    }

    @Override
    public int compareTo(Object o)
    {
        return new Integer(time).compareTo((Integer)((RaceResult)o).time);
    }       

    @Override
    public String toString()
    {
        return name + "(" + time + ")";
    }
}

And the Marathon class:

class Marathon {
    List<RaceResult> results = Arrays.asList(new RaceResult("Elena", 341),
                                             new RaceResult("Thomas", 273),
                                             new RaceResult("Hamilton", 278));

    public static void main(String[] args)
    {
        Collections.sort(results);
        System.out.println("Winner: " + results.get(0));
        System.out.println("2nd place: " + results.get(1));
    }
}
Mike B
  • 5,390
  • 2
  • 23
  • 45
0

One way that you can do this without making a special class: iterate through your array in a for loop and find the max value by comparing each element of your int array to a "max" variable, then once you found the maximum, save it, delete that entry from the array, and then scan again for the max.... which this time will be the second to largest number, since the first largest number was already removed.

Drifter64
  • 1,103
  • 3
  • 11
  • 30
0

You can just loop through the array O(n)

Edit: read the question to wrong... With 2 Math.max I would recommend just using an if test.

int[] times = {
        341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
        343, 317, 265
    };

Integer max1 = null, max2 = null;
for(int i=0;i<times.length;i++) {
    if(max2 == null || max1 == null || max1 <= times[i]) {
        max2 = max;
        max1 = times[i];
    }
}
System.out.println("max1: " + max1 + " max2: " + max2);
ug_
  • 11,267
  • 2
  • 35
  • 52