Q:

Java Program to find Second Largest Number in an Array

belongs to collection: Java Array Programs

0

We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number. 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public class SecondLargestInArrayExample{  
public static int getSecondLargest(int[] a, int total){  
int temp;  
for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[total-2];  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,33,22,55};  
System.out.println("Second Largest: "+getSecondLargest(a,6));  
System.out.println("Second Largest: "+getSecondLargest(b,7));  
}}  

 

Output:

Second Largest: 5
Second Largest: 77

 

Find 2nd Largest Number in Array using Arrays

Let's see another example to get second largest element or number in java array using collections.

import java.util.Arrays;  
public class SecondLargestInArrayExample1{  
public static int getSecondLargest(int[] a, int total){  
Arrays.sort(a);  
return a[total-2];  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,33,22,55};  
System.out.println("Second Largest: "+getSecondLargest(a,6));  
System.out.println("Second Largest: "+getSecondLargest(b,7));  
}}  

 

Output:

Second Largest: 5
Second Largest: 77

 

Find 2nd Largest Number in Array using Collections

Let's see another example to get second largest number in java array using collections.

import java.util.*;  
public class SecondLargestInArrayExample2{  
public static int getSecondLargest(Integer[] a, int total){  
List<Integer> list=Arrays.asList(a);  
Collections.sort(list);  
int element=list.get(total-2);  
return element;  
}  
public static void main(String args[]){  
Integer a[]={1,2,5,6,3,2};  
Integer b[]={44,66,99,77,33,22,55};  
System.out.println("Second Largest: "+getSecondLargest(a,6));  
System.out.println("Second Largest: "+getSecondLargest(b,7));  
}}  

 

Output:

Second Largest: 5
Second Largest: 77

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Program to find Second Smallest Number in an ... >>
<< Java Program to find Third Largest Number in an Ar...