Home Java Java-tips Data Arrays Array - Maximum

Ask Questions?

View Latest Questions

Advertisement


 
 

Array - Maximum
Posted on: July 26, 2006 at 12:00 AM
There is one common variation on this -- sometimes it isn't the maximum value that is desired, but the index of the maximum value.

Java Notes

Array - Maximum

Finding the maximum is basically the same as finding the minimum; remember the first value, then look through all the other elements. Whenever a larger (smaller) value is found, that becomes the new maximum (minimum).

There is one common variation on this -- sometimes it isn't the maximum value that is desired, but the index of the maximum value (eg, so it can be changed).

//===================================================== max
public static int max(int[] t) {
    int maximum = t[0];   // start with the first value
    for (int i=1; i<t.length; i++) {
        if (t[i] > maximum) {
            maximum = t[i];   // new maximum
        }
    }
    return maximum;
}//end method max

To make this work with object types (eg String), you will have to change the type declarations of course, but you will also have to change the comparison to use .compareTo(), which must be defined for that object type.

A minor problem with this algorithm is what to do if there are absolutely no elements in the array -- t.length is zero? This will produce an error when we try to get that first element. One solution is to throw an Exception. Another is to change this to return the index, and when there are no elements return an impossible index (eg, -1). Many programmers won't worry about this case because it will be impossible for their program. However, you should always think about the possibility of an empty array.

Loop direction

Very rarely you will find a programmer who prefers to write loops that go from high to low. Of course it makes no difference in this algorithm, however, there are machines in which that can save a few nanoseconds. This is enough harder for humans to read that it is generally considered antisocial without a good reason (and it's not common to find a good reason).

Copyleft 2003 Fred Swartz MIT License, Last update: 2003-02-27
Advertisement


DMCA.com