Find Second Largest Number in Array

We can find second largest number in array using arrays , collections and sorting techniques . We will discuss how to find second largest number in array using these method with example steps by steps  .

Java Program to Find Second Largest Number in Array

We will write a java program to find second largest element in array using simple approach as below

Approach: The approach is to traverse the array twice.   In the first traversal find the maximum element in array . In the second traversal find the greatest element in the remaining array excluding the previous greatest.

public class SecondLargestElementSimple {

	// Function to print the second largest elements
	static void print2largest(int arr[], int arr_size)
	{
	    int i, first, second;
	 
	    // There should be atleast two elements
	    if (arr_size < 2)
	    {
	        System.out.printf(" Invalid Input ");
	        return;
	    }
	 
	    int largest = second = Integer.MIN_VALUE;
	 
	    // Find the largest element
	    for(i = 0; i < arr_size; i++)
	    {
	        largest = Math.max(largest, arr[i]);
	    }
	 
	    // Find the second largest element
	    for(i = 0; i < arr_size; i++)
	    {
	        if (arr[i] != largest)
	            second = Math.max(second, arr[i]);
	    }
	    if (second == Integer.MIN_VALUE)
	        System.out.println("There is no second " +
	                          "largest element");
	    else
	        System.out.println("The second largest " +
	                          "element is :"+ second);
	}
	
	public static void main(String[] args) {
		  int arr[] = {1,2,5,6,3,2};  
		  int n = arr.length;
		  print2largest(arr, n);
	}
	
}

Output :

Second Largest is : 5

A more Efficient Solution can be to find the second largest element in a single traversal.
Below is the complete algorithm for doing this:

1) Initialize the first as 0(i.e, index of arr[0] element
2) Start traversing the array from array[1],
a) If the current element in array say arr[i] is greater
than first. Then update first and second as,
second = first
first = arr[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = arr[i]
3) Return the value stored in second.

Now we will implement this algorithms in java


public class SecondLargestElementEfficiently {

	//print second largest number 
    public static void print2largest(int arr[],
	                                     int arr_size)
	    {
	        int i, first, second;
	 
	        /* There should be atleast two elements */
	        if (arr_size < 2) {
	            System.out.print(" Invalid Input ");
	            return;
	        }
	 
	        first = second = Integer.MIN_VALUE;
	        for (i = 0; i < arr_size; i++) {
	            /* If current element is greater than
	            first then update both first and second */
	            if (arr[i] > first) {
	                second = first;
	                first = arr[i];
	            }
	 
	            /* If arr[i] is in between first and
	               second then update second  */
	            else if (arr[i] > second && arr[i] != first)
	                second = arr[i];
	        }
	 
		    if (second == Integer.MIN_VALUE)
		        System.out.println("There is no second " +
		                          "largest element");
		    else
		        System.out.println("The second largest " +
		                          "element is :"+ second);
	    }
	    
	
	public static void main(String[] args) {
		  int arr[] = {1,2,5,6,3,2};  
		  //length of array
		  int n = arr.length;
		  print2largest(arr, n);
	}
	
}

Output :

The second largest element is :5

Find Second Largest Number in Array using Arrays

In this example we will find second largest number in array using arrays . We use arrays sort() method to sort array in acceding order then print  arr_size – 2  element .

import java.util.Arrays;

public class SecondLargestElementUsingArrays {
	
	 
	// Function to print the second largest elements
	static void print2largest(int arr[], int arr_size)
	{
		if (arr_size < 2)
		  {
		    System.out.printf(" Invalid Input ");
		    return;
		  }
		
		 // Sort the array
		  Arrays.sort(arr);
		
		  System.out.println("Second Largest is : "+ arr[arr_size-2]);
		  
	}
	
	public static void main(String[] args) {
		  int arr[] = {1,2,5,6,3,2};  
		  int n = arr.length;
		  print2largest(arr, n);
	}

}

Output :

Second Largest is : 5

Find Second Largest Number in Array using Collections

Now we write a java program to find second largest number in array using collections

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SecondLargestElementUsingCollections {

	// Function to print the second largest elements
		static void print2largest(Integer arr[], int arr_size)
		{
			if (arr_size < 2)
			  {
			    System.out.printf(" Invalid Input ");
			    return;
			  }
			
			List<Integer> list=Arrays.asList(arr);  
			Collections.sort(list);  
			System.out.println("Second Largest is : "+ list.get(arr_size-2));
			  
		}
		
		public static void main(String[] args) {
			Integer arr[] = {1,2,5,6,3,2};  
			int n = arr.length;
			print2largest(arr, n);
		}
		
}

Output :

Second Largest is : 5

In this tutorial we have learned various method for how to find second largest number in array in java . You keep learning java interview program with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *

56 − 48 =