> How do i find the max value of a bunch of numbers in java?

How do i find the max value of a bunch of numbers in java?

Posted at: 2014-12-18 
Sure, recursion, keep spliting down array; each split will be smaller in length, with base case being array of 1 size; then compare. That works easiest with even length but with little tweak all length odd or even works.

Or sort, depending what it does either end or beginning.

You would use a loop. Only one number is the maximum seen thus far.

If you know the range of random values is limited then you can initialize the maximum to be less than the smallest value in the range.

public class Program {

public static void main(String[] args) {

int[] rnds = {1, 9, 2, 8, 3, 7, 4, 6};

int max = getMax(rnds);

System.out.println(max);

}



private static int getMax(int[] values) {

int result = values[0];

for(int i = 1; i < values.length; i++) {

result = Math.max(result, values[i]);

}

return result;

}

}

Just use a loop.

public static int getBiggest(int[] items)

{

if (items == null || items.length == 0) throw IllegalArgumentException();

int result = items[0];

for (int i = 1; i < items.length; i++)

{

if (result < items[i]) {

result = items[i]

}

}

return result;

}

I have 8 random values i need to compare and find the maximum one. However the only method i know of comparing more than 2 numbers is Math.max(Math.max(x,y),z). This is relatively simple, however it gets incredibly long and complicated when doing more than 3 or 4 numbers. Is there an easier way?