Home > database >  finding the index of max and min in an array
finding the index of max and min in an array

Time:06-02

This is my code. I am using the bluej IDE.

    public class practice
    {
public int[] minMax(int[] num) {  
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i  ){
    if (num[i] < smallest) smallest = num[i];
    if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i  ){
    if (num[i] != smallest) countsmall  ;
    if (num[i] != largest) countlarge  ;
}
int array[] = {countsmall,countlarge};
return array;
}
}

I am trying to find the minimum and maximum value in an array which I successfully did. After that,I am trying to find its index. I created a variable count, and then went through the array. If that item in the array does not equal the minimum or maximum value, count = count. However, for some reason its not working. The code compiles but returns the wrong value. Keep in mind I am not allowed to use java libraries. Any help would be much appreciated, thanks.

CodePudding user response:

If you want also indexes of biggest and smallest, why dont you do it in one loop? eg:

public class practice
{
    public int[] minMax(int[] num) {  
      int smallest = num[0];
      int largest = num[0];
      int countsmall = 0;
      int countlarge = 0;
      for (int i = 0; i < num.length; i  ){
        if (num[i] < smallest) {
            smallest = num[i];
            countsmall=i;
        }
        if (num[i] > largest) {
            largest = num[i];
            countlarge=i;
        }
      }
    
      int array[] = {countsmall,countlarge};
      return array;
    }
}
  •  Tags:  
  • java
  • Related