How to find second largest number in an array in Java

Hello Everyone, here we will learn about how to find the second largest number in an array in Java. In order to do this, we have to perform a bubble sorting method and set the array in descending order.

Java program: find the second largest number using bubble sort

public class Main
{
  public static void main(String[] args) {
    int[] a={1,23,12,5,8,9};
    int i,j;
          int n=a.length;
    for (i = 0; i < n-1; i++)     
               {     for (j = 0; j < n-i-1; j++)  
                    {
                       if (a[j] < a[j+1])  
                      {
                          int temp=a[j];
                          a[j]=a[j+1];
                          a[j+1]=temp;
                      }
                    }
                }  
    System.out.println(a[1]);
       }
}

Output:12

First, declare and initiate an array with any number of elements you want to using “int[] a={numbers}”.Then declare i, j variables and now declare a variable ‘n’ of type “integer”. Use the length method in order to count the number of elements in an array that we have declared above. “a.length” method is used above. Use the bubble sort technique to sort the elements. In bubble sort, we use 2 variables i and j and then compare all the elements one by one. And here we use the swapping method while comparing. So now everything is sorted, here we have sorted the array elements in descending order. The first element is the first largest number which is at the index at ‘0’.  Then it is clear that the second largest number is at index ‘1’. Now print the second largest number by using a[1]. It is obvious that the array index always starts from index ‘0’. We can sort the array in ascending order and fetch the second largest number by indexing at the position which is second from last that is n-2.

I hope the explanation is clear and we can use any sorting technique and find the second-largest number.

Leave a Reply