How would i find the maximum value in an array? [d

2019-01-14 20:00发布

问题:

This question already has an answer here:

  • Java: Finding the highest value in an array 14 answers

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?

回答1:

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);
    }
}


回答2:

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];
      }
}


回答3:

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.