I am trying to get the indices of large numbers within an array and I am having trouble doing so.. My code works if there is only one large number in the array. However, if there is one or more of the same large number, it does not works.
For example,
- if I have an array
{2,1,1,2,1}
, it should return me the index 0 and 3 (this does not) - if I have an array
{2,1,3,2,1}
, it will then return me index 2. (this works)
Currently, I am trying to store the index by making use of an array, however in my code, as given in my example above, it only returns me the index of the first large number it found.
My code:
class Main {
public static void getIndexOfMax(int array[]) {
int max = array[0];
int pos = 0;
int max_index[] = new int[array.length];
int counter = 0;
for(int i=1; i<array.length; i++) {
if (max < array[i])
{
pos = i;
max = array[i];
max_index[counter] = pos;
counter += 1;
}
}
public static void main(String[] args) {
int[] num = {2,1,1,2,1};
getIndexOfMax(num);
}
}
Thanks in advance for any replies!