1

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!

j.hall
  • 61
  • 5
  • Duplicated of https://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-element-in-array/20798567 hope it works, if not let me know. – German Reynaga Oct 15 '20 at 04:42

2 Answers2

1

You can have another conditional stating, if max is equal to an array element, then store that element index also. Then you would have to declare another array for the max index positions. `if (max < array[i]) {

pos = i;

indexStorage.add(pos)

max = array[I];

max_index[counter] = pos;

counter += 1; }`

Kenny A
  • 34
  • 1
1

You need to check another case when you find the maximum value again and store the index. And when the new maximum value starts the counter from 0 again.

  public static void printIndexOfMax(int array[]) {
    int max = 0;
    int max_index[] = new int[array.length];
    int counter = 0;

    for (int i = 0; i < array.length; i++) {
      if (max <= array[i]) { // Allowing same maximum number
        if (max < array[i])  // Start counter from 0 when new maximum value found
            counter = 0;
        max = array[i];
        max_index[counter] = i;
        counter++;
      }
    }
    for (int i = 0; i < counter; i++) {
      System.out.println(max_index[i]);
    }
  }
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • 1
    Thank you, had not thought of using the counter to re-check if it is the same maximum number. – j.hall Oct 15 '20 at 04:54