The title above sums up my question, to clarify things an example is:
array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
so the result I would like is 2, since it contains the largest element 7.
The title above sums up my question, to clarify things an example is:
array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
so the result I would like is 2, since it contains the largest element 7.
int maxAt = 0;
for (int i = 0; i < array.length; i++) {
maxAt = array[i] > array[maxAt] ? i : maxAt;
}
1 :) Also you can't differentiate between empty array and one element array.public int getIndexOfLargest( int[] array )
{
if ( array == null || array.length == 0 ) return -1; // null or empty
int largest = 0;
for ( int i = 1; i < array.length; i++ )
{
if ( array[i] > array[largest] ) largest = i;
}
return largest; // position of the first largest found
}
largest.indexOfLargest would suffice as a single, self-explanatory variable.int indexOfLargest = 0; for ( int i = 0; i < array.length; i++ ) { if ( array[i] > array[indexOfLargest] ) { indexOfLargest = i; }}. Basically the same as ifLoop's answer.1, not 0.one way will be:
Integer[] array = new Integer[4];
array[0] = 1;
array[1] = 3;
array[2] = 7;
array[3] = 5;
List<Integer> iList = Arrays.asList(array);
System.out.println(iList.indexOf(Collections.max(iList)));
System.out.println(iList.indexOf(Collections.min(iList)));
Integers. Sadly in many cases it's not and there isn't a pleasant way to move between the two (without external libs).Two lines code will do that in efficient way
//find the maximum value using stream API of the java 8
Integer max =Arrays.stream(numbers) .max(Integer::compare).get();
// find the index of that value
int index = Arrays.asList(numbers).indexOf(max);
Would do it like this (as I don't know any predefined function to get the index of highest element, only the element itself, of course you could get the index with list.indexOf(element) then, but array needs to be converted to list and 2 iterations):
maxIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > array[maxIndex]) {
maxIndex = i;
}
}