Finding the index of the largest element in an array is relatively easy. I remember seeing a couple free response questions in the AP Computer Science Exam that involved this type of problem too, so it’s good to know.
You’ll need an array full of numbers, those could be integers, doubles, longs, whatever, as long as it is comprised of a number. My solution uses two data keeping variables, largest
and index
. The largest
variable will keep track of the biggest value in the array while the index
variable keeps track of where the largest value was found.
Optionally, I like to set the largest
and index
variables before I start any testing. largest
is set to array[0]
and index
is set to 0
so that we can skip that initial value.
int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 30}; int largest = array[0], index = 0; for (int i = 1; i < array.length; i++) { if ( array[i] > largest ) { largest = array[i]; index = i; } }
This will set index
to 5 because 49 is the largest in the array.
If there had been two instances of 49 in the array, which would have been returned? The first one as the code stands. To change it, one would simply have to change the conditional from greater than to equals or greater than.
int[] array = {29, 42, 1, 32, 44, 49, 0, 13, 43, 49}; int largest = array[0], index = 0; for (int i = 1; i < array.length; i++) { if ( array[i] >= largest ) { largest = array[i]; index = i; } }
This would set index
to 9 because 49 is the last largest in the array.
Wouldn’t it be nice of Java had a method that did this for you? Like: Arrays.largest
or Arrays.smallest
which would work for primitive numeric values. Simple and obvious.
Happy indexing.