Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum value in an array? [duplicate]

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?

like image 398
Haneef Kazi Avatar asked Nov 27 '22 03:11

Haneef Kazi


1 Answers

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);
    }
}
like image 141
Philip Avatar answered Dec 05 '22 16:12

Philip