Search code examples
javaarrayssortingfind-occurrences

How do I print all the occurrences of the greatest two integers in an array?


I am trying to print the occurrences of the two highest integers in an integer array but the output keeps coming out with the top three.

Integer[] scores = {4,4,4,6,6,4,2,3};
        Arrays.sort(scores, Collections.reverseOrder());

        int flag = 0;
        System.out.println(scores[0]);
        int first = scores[0];

        for (int i = 1; i < scores.length; i++) {;
            if(first == scores[i]) {
                System.out.println(scores[i]);
            }else {
                first = scores[i];
                flag++;
                System.out.println(scores[i]);
            }
            if(flag == 2) {
                break;
            }
        }

Is there a better way to have them print? They are currently printing out as 6 6 4 4 4 4 3. The correct output should be 6 6 4 4 4 4


Solution

  • The problem is the System.out.println(scores[i]) after you increment the flag to be 2. You shouldn't be printing when this is the third number in the list.

    I've changed/simplified the code as

    int flag = 0;
    int first = scores[0];
    for (int i = 0; i < scores.length; i++) {
        if(first != scores[i]) { //Encountering second number
            first = scores[i];
            flag++;
        }
        if(flag == 2) { //If already seen three numbers, break
            break;
        }
        System.out.println(scores[i]); //Good to print it
    }
    

    It is more intuitive to rename first as number or something else as it can hold the first or the second number.