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?
Asked
Active
Viewed 2.5e+01k times
4
-
1Can you show us what you have tried so far? – NilsH May 01 '13 at 19:41
-
1We're not here to do homework for you. – David May 01 '13 at 19:41
-
2Im sorry i figured it out and i forgot to put my code up their but im fine now – Haneef Kazi May 01 '13 at 20:05
-
I found this solution very effective using javascript `function myArrayMax(arr) { return Math.min.apply(null, arr); }` – monikapatelIT Oct 03 '18 at 22:30
3 Answers
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
-
-
1if it is an ArrayList it is `arraylist.get(0)` if it an array it is `array[0]` – Fed Nov 04 '16 at 04:35
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
-
15Sorting 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