How to print the top 3 largest values from array in Java

1 Answer

0 votes
public class MyClass {
    static void printTop3(int arr[]) {
        int first, second, third;
        int len = arr.length;
  
        if (len < 3) {
            return;
        }
  
        first = second = third = Integer.MIN_VALUE;
        for (int i = 0; i < len; i++) {
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }
            else if (arr[i] > second) {
                third = second;
                second = arr[i];
            }
  
            else if (arr[i] > third)
                third = arr[i];
        }
  
        System.out.println(first + " " + second + " " + third);
    }
  
    public static void main(String args[]) {
        int arr[] = { 12, 98, 80, 50, 88, 35, 70, 60, 97, 85, 89 };
 
        printTop3(arr);
    }
}
 
 
 
 
/*
run:
 
98 97 89
 
*/

 



answered Jun 9, 2021 by avibootz
edited Jun 9, 2021 by avibootz

Related questions

1 answer 146 views
1 answer 149 views
1 answer 153 views
1 answer 129 views
2 answers 168 views
1 answer 202 views
2 answers 167 views
...