16

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.

9
  • 8
    What you have tried so far? Commented Apr 7, 2014 at 11:56
  • 2
    possible duplicate of How to find the largest int in an array using java Commented Apr 7, 2014 at 11:57
  • 1
    This is a trivial thing to do actually. There are a lot of searching algorithms for this, have you even tried something? Commented Apr 7, 2014 at 11:57
  • 1
    there are simpler (and quicker) things than sorting... Commented Apr 7, 2014 at 11:58
  • 3
    Down-vote from me - I expect to see some effort on your part. This is not a difficult challenge. Commented Apr 7, 2014 at 12:01

9 Answers 9

25
int maxAt = 0;

for (int i = 0; i < array.length; i++) {
    maxAt = array[i] > array[maxAt] ? i : maxAt;
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Duncan Thanks for the hint, fixed this
@ifLoop, it's not fixed. The first iteration of the loop will crash with an exception (-1 out of range) ... edit: I see that you've corrected that now.
@Duncan, sorry I did get you and the author mixed up - my bad.
It might be neatest, if you would start your loop with 1 :) Also you can't differentiate between empty array and one element array.
As suggested by Boris, starting at one makes sense.
15
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
}

7 Comments

You don't need to store largest.
@Duncan, true but it is a little more "readable" when you do ;)
Agree to disagree :-) I think indexOfLargest would suffice as a single, self-explanatory variable.
I wouldn't have thought so. For the avoidance of doubt, this is what I'm suggesting (copy into IDE to format nicely!): 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.
@Duncan I would start the loop with 1, not 0.
|
5

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)));

4 Comments

This does not find the index.
This is a nice solution if the array was already of Integers. Sadly in many cases it's not and there isn't a pleasant way to move between the two (without external libs).
what if the values are repeatable.
If the values are repeatable the first occurence of index with repeated value will be considered.
3

Using Java 8 streams:

    List<Integer> list = Arrays.asList(1, 3, 7, 5);
    IntStream.range(0, list.size())
            .reduce((i, j) -> list.get(i) > list.get(j) ? i : j)
            .getAsInt();

Comments

2
public int getIndexOfMax(int array[]) {
    if (array.length == 0) {
        return -1; // array contains no elements
    }
    int max = array[0];
    int pos = 0;

    for(int i=1; i<array.length; i++) {
        if (max < array[i]) {
            pos = i;
            max = array[i];
        }
    }
    return pos;
}

Comments

2

Please find below code for the same

Integer array[] = new Integer[4];
array[0] = 1;
array[1] = 3;
array[2] = 7;
array[3] = 5;

List < Integer > numberList = Arrays.asList(array);

int index_maxNumber = numberList.indexOf(Collections.max(numberList));

System.out.println(index_maxNumber);

Comments

1

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);

1 Comment

The most elegant solution so far but due to Java streams implementation, not very efficient. C# does a better job with the IEnumerable interface implemented by arrays.
1

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);

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.