Find Second largest element in an array | Java program to find second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; Sort the array ; Start from second last element as the largest element is at last ; If the element is not equal to largest element ; Driver code
import java . util . * ; class GFG { static void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { System . out . printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } Arrays . sort ( arr ) ; for ( i = arr_size - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] != arr [ arr_size - 1 ] ) { System . out . printf ( " The ▁ second ▁ largest ▁ " + "element is %dNEW_LINE", arr[i]); return ; } } System . out . printf ( " There ▁ is ▁ no ▁ second ▁ " + "largest elementNEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = arr . length ; print2largest ( arr , n ) ; } }