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?
This question already has an answer here:
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?
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);
}
}
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];
}
}
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.