indices != values
newbie's code almost works. The only case it won't work is if the highest value happens to be 0. There's no need to store the highest value and the position. Furthermore, except for an array of size 0 there is always guaranteed to be at least one value which is the largest (or in this case, most positive). How you handle multiple highest values in the list is up to you, though usually you would just return the first one you find.
public static int max(int[] numbers)
{
if(numbers.length == 0)
{
return -1; // no numbers to find the max of
}
int highestIndex = 0;
for(int i = 1; i < numbers.length; ++i)
{
if(numbers[i] > numbers[highestIndex)
{
highestIndex = i;
}
}
return highestIndex;
}
Test cases:
System.out.println(max(new int[]{1, 2, 3, 4})); // prints 3
System.out.println(max(new int[]{})); // prints -1
System.out.println(max(new int[]{-1, 0})); // prints 1
System.out.println(max(new int[]{-1, -3, -6 ,-1, 3, 100, 50})); // prints 5