Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find array index of largest value?

Tags:

java

arrays

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.

like image 368
user3307418 Avatar asked Apr 07 '14 11:04

user3307418


People also ask

How to find the largest element in an array?

Given an array, find the largest element in it. Example: The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max.

How do you get the max value of an array?

To get the index of the max value in an array: Get the max value in the array, using the Math.max () method. Call the indexOf () method on the array, passing it the max value. The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found.

How do you find the max value of an index variable?

Declare an indexes variable that stores an empty array. Iterate over the array and push only the indexes of the max values to the indexes array. We used a for loop to iterate for array.length iterations. On each iteration, we check if the element at that index is the max value, and if it is, we push the current index to the indexes array.

How to get the index of the max value in NumPy?

The following code shows how to get the index of the max value in a one-dimensional NumPy array: The argmax () function returns a value of 2. This tells us that the value in index position 2 of the array contains the maximum value.


2 Answers

int maxAt = 0;

for (int i = 0; i < array.length; i++) {
    maxAt = array[i] > array[maxAt] ? i : maxAt;
}
like image 163
ifloop Avatar answered Sep 24 '22 17:09

ifloop


Another functional implementation

int array[] = new int[]{1,3,7,5};        

int maxIndex =IntStream.range(0,array.length)
              .boxed()
              .max(Comparator.comparingInt(i -> array[i]))
              .map(max->array[max])
              .orElse(-1);
like image 43
David Lilljegren Avatar answered Sep 22 '22 17:09

David Lilljegren