Find First and Second Largest Number in Array

Find First And Second Largest Number In Array | In this blog, we write the java program to find the largest and the next largest number in the given array. For example:-

1) array[ ] = {1, 2, 3, 4, 5}
Largest number = 5
The second-largest number = 4

2) array[ ] = {90, 49, -90, 34, 87}
Largest number = 90
Second largest number = 87

Java Program To Find First and Second Largest Number in Array

In this program, we have not used any built-in. methods available in Java. We have two variables initialized to a minimum and maximum and iterate the array. Then compare each number with the first element. If the first element is lesser than the element initialize the element to the first variable likewise check for the second number and then return the elements which are first largest and second-largest.

public class Main {

   public static void main(String[] args) {
      int array[] = { 78, 98, 45, 12, 36, 45, 79, 12, 10 };
      int first = Integer.MIN_VALUE;
      int second = Integer.MIN_VALUE;

      for (int i = 0; i < array.length; i++) {
         if (first < array[i]) {
            second = first;
            first = array[i];
         } else if (second < array[i]) {
            second = array[i];
         }
      }
      System.out.println("Top two numbers: \nFirst: " 
                     + first + "\nSecond: " + second);
   }
}

Output:-

Top two numbers:
First: 98
Second: 79

Java Program to Find First and Second Largest Number in Array Using User-Defined Function

In the below Java program to find first and second largest number in array we have defined a user-defined method. In this method first, we have checked whether the array of more than 2 elements or not.

public class Main {

   public static void largestTwoElements(int[] array) {
      if (array.length < 2) {
         System.out.println("Invalid Input, "
                +"array size is less than 2");
      }

      int first = Integer.MIN_VALUE;
      int second = Integer.MIN_VALUE;

      for (int i = 0; i < array.length; i++) {
         int current = array[i];
         if (first < current) {
            second = first;
            first = current;
         } else if (second < current) {
            second = current;
         }
      }
      System.out.println("The first and second largest " + 
               "elements are: " + first + " " + second);
   }

   public static void main(String[] args) {
      int[] array = { 45, 25, 12, 69, 78, 36, 47, 12, 56 };
      largestTwoElements(array);
   }
}

Output:-

The first and second largest elements are: 78 69

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *