javaarrays

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?


Solution

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

    max3 = max2