Maximum element in an array in java

Posted By: Java Examples - 7:28 PM

Share

& Comment

To find the maximum value in an array :

  1. Assign the first (or any) array element to the variable that will hold the maximum value
  2. Loop through the remaining array elements, starting at the second element (subscript 1). When a larger value is found, that becomes the new maximum.
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. The minimum can be found by the same algorithm, simply inverting the test. It's also easy to add a test for the minimum to this loop so that both the maximum and minimum are determined within the same loop. 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).

Java version of the Maximum element problem is given below :
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package array;

/**
 *
 * @author ACHCHUTHAN
 */
public class MaxElement {

    public static void main(String args[]) {
        int[] array = {45, 66, 77, 54, 76, 89, 86, 45, 67, 87};
        //assign the first element as maximum
        int maximum = array[0];
        // start with the first value
        int index = -1;
        //Find maximum (largest) value in array using loop  
        for (int i = 1; i < array.length; i++) {
            if (array[i] > maximum) {
                maximum = array[i];
                // new maximum
                index = i;
            }
        }
        System.out.println("Maximun element : " + maximum + 
                              "\nIndex of Maximum : " + index);
    }
}

Output of this program is given bellow :

run:
Maximun element is : 89
Index of Maximum is : 5
BUILD SUCCESSFUL (total time: 1 second)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .