简体   繁体   中英

Find 3 max integers in an array

I tried to find largest three elements in an array. So far I've come up with this but it doesn't work properly (The output is 9 8 3):

public class Test {

    public static void main(String[] args) {
        int max1, max2, max3;
        int[] test= {2,4,8,3,9,1};
        
        max1= test[0];
        max2= test[0];
        max3= test[0];
        for(int i = 1; i < test.length; i++) {
            if(max1 < test[i]) {
                max2= max1;
                max1= test[i];
            }
            else if (max2 < test[i]) {
                max3= max2;
                max2= test[i];
            }
            else if (max3 < test[i]) {
                max3= test[i];
            }

        }
        System.out.println(max1 + " " + max2 + " " + max3);
        
    }

}

I've managed to do the largest 2 integers but I can't do 3. How can I write the code using only 1 iteration through the array?

In the first 'if' statement you do not include:

max3 = max2

I would use stream s for that job:

int[] test= {2,4,8,3,9,1};

String maxValues = Arrays.stream(test).boxed()
        .sorted(Comparator.reverseOrder())
        .limit(3)
        .map(String::valueOf)
        .collect(Collectors.joining(" "));

System.out.println(maxValues);

Output

9 8 4
    Arrays.sort(test);
    max1 = test[test.length - 1];
    max2 = test[test.length - 2];
    max3 = test[test.length - 3];
    System.out.println(max1 + " " + max2 + " " + max3);

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