简体   繁体   中英

How to find the position of the highest and second highest value in an array in java

Let's assume that we have an array with integer numbers. For Example perimeter={180,50,65,78,90,5,150,2,35} and i want to find the highest value and its position in the array and the second value and its position in the array.

public class FindTopTwo {

public static void main(String[] args) {
    double perimeter[]= {180,50,65,78,90,5,150,2,35};
    double megisto, megisto2;
    int i;
    megisto=perimeter[0];
    megisto2=perimeter[0];
    for (i=0;i<perimeter.length;i++) {
        if (perimeter[i]>megisto) {
            megisto2=megisto;
            megisto=perimeter[i];}
        else if (perimeter[i]>megisto2) {
            megisto2=perimeter[i];
        }
    }
    System.out.println("the first is:"+megisto+"the second highest value is "+megisto2);    

   }

}

Just keep track of their indexes( i ) as their values change:

public static void main(String[] args) {
    double perimeter[]= {180,50,65,78,90,5,150,2,35};
    double megisto, megisto2;
    megisto=perimeter[0];
    int megistoIndex = 0;

    megisto2=perimeter[0];

    int megisto2Index = 0;

    for (int i=0;i<perimeter.length;i++) {
        if (perimeter[i]>megisto) {
          megistoIndex = i;
          megisto = perimeter[i];
        } else if (perimeter[i] < megisto && perimeter[i] > megisto2) {
          megisto2Index = i;
          megisto2 = perimeter[i];
        }

    }
    System.out.println(String.format("the first is: %d at index %d. The second highest value is %d at index %d", megisto, megistoIndex, megisto2, megisto2Index));
}
set highestIndex = -1;
set nextHighestIndex = -1;

for every element of perimiter:

  if highestIndex = -1:
    set highestIndex = i;
  else if perimiter[i] > perimiter[highestIndex]
    set nextHighestIndex = highestIndex;
    set highestIndex = i;
  else if perimiter[i] > perimieter[nextHighestIndex]
    set nextHighestIndex = i;

If the array is not empty, you will find the highest value in perimiter[highestIndex]

If the array has at least two distinct values, you will find the second highest value in perimeter[nextHighestIndex]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM