4

In java, i need to be able to go through an array and find the max value. How would I compare the elements of the array to find the max?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Haneef Kazi
  • 205
  • 2
  • 3
  • 5

3 Answers3

17

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}
Cryptoclysm
  • 117
  • 13
Philip
  • 2,287
  • 1
  • 22
  • 37
15

If you can change the order of the elements:

 int[] myArray = new int[]{1, 3, 8, 5, 7, };
 Arrays.sort(myArray);
 int max = myArray[myArray.length - 1];

If you can't change the order of the elements:

int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
      if(myArray[i] > max) {
         max = myArray[i];
      }
}
Daniel Pereira
  • 2,720
  • 2
  • 28
  • 40
  • 15
    Sorting is a bad idea unless performance is of no concern. Sorting is O(n log n) whereas iterating over the array once is only O(n). – devconsole Apr 07 '16 at 09:48
2

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176