Second Largest Element


Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.
Example:

Input : arr[] = {12, 35, 1, 10, 34, 1}
Output : The second largest element is 34.

Code:

package sap;

public class SecondLargest {
   
    public static void main(String[] args){
       
        int[] a = {89, 24, 75, 11, 23};
        int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE;
       
        for(int i=0; i<a.length; i++){
           
            if(a[i] > max){
               
                secondMax = max;
                max = a[i];
               
            }
            else if(a[i] > secondMax){
                secondMax = a[i];
            }
           
        }
       
        System.out.println("The second maximum element is "+secondMax);
       
    }

}



Output:

The second maximum element is 75

Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Check if a number is a power of another number