Write a program to find second largest number in an array.

Write a program to find second largest number in an array.

Program to find the second largest element of an array.

Solution :

Algorithm :

  1. Find the maximum number of the array.

  2. Replace the maximum number with the smallest integer value.

  3. Find the maximum again.

import java.util.Scanner;

public class secondMax {
    static int findMax(int [] arr){
        int max = Integer.MIN_VALUE;
        for(int i=0; i<arr.length; i++){
            if (arr[i] > max){
                max = arr[i];
            }
        }
        return max;
    }

    static int findSecondMax(int [] arr){
        int max = findMax(arr);
        for(int i=0; i<arr.length; i++){
            if(arr[i] == max){
                arr[i] = Integer.MIN_VALUE;
            }
        }
        int secondMax = findMax(arr);
        return secondMax;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number of elements : ");
        int n = scan.nextInt();
        int [] arr = new int [n];
        System.out.println("Enter the elements :");
        for(int i=0; i<arr.length; i++){
            arr[i] = scan.nextInt();
        }
        int secondMax = findSecondMax(arr);
        System.out.println("The second max number is : "+secondMax);
    }
}