Java program to find second largest number in an array



Step 1:

    Iterate the given array

Step 2 (first if condition arr[i] > largest):

    If current array value is greater than largest value then

        Move the largest value to secondLargest and make

        current value as largest

Step 3 (second if condition arr[i] > secondLargest )  

  If the current value is smaller than largest and greater than secondLargest  then

        the current value becomes secondLargest


Program

package com.candidjava;

public class SecondLargest {

	public static void main(String[] args) {

		int arr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
		int largest = arr[0];
		int secondLargest = arr[0];
		
		System.out.println("The given array is:" );
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i]+"\t");
		}
		for (int i = 0; i < arr.length; i++) {

			if (arr[i] > largest) {
				secondLargest = largest;
				largest = arr[i];

			} else if (arr[i] > secondLargest) {
				secondLargest = arr[i];

			}
		}

		System.out.println("\nSecond largest number is:" + secondLargest);

	}
}

Output

The given array is:

14 46 47 86 92 52 48 36 66 85

Second largest number is:86


Related example

        Java program to find largest number in an array
        Java program to find second largest number in an array
        Java program to find largest and smallest number in an array
        Java program to find largest and second largest number in an array
        Java program to find second smallest number in an array
        Java program to find index of max value in array java
        Java program to find index of smallest element in array java



Related Post

Comments

Suresh Sala
         It s wrong.. {5,4,3,2,1} it is showing output 5
Mohammad Javed
         The Above solution will not work if the Largest element is at array[0]. So, we should initialize the secondLargest and largest to zero. (The best approach will be to find the minimum in the array and then initialize it with min )
vishal
         Agree with Suresh and Javed
Ali Umar
         It is working fine. Thanks
PRADEEP KUMAR PALAI
         I completely agree with javed :) public static int secondLargestElement(int arr[]) { int lengtharr = arr.length; int secondlargest = 0; int lagest = 0; //displaying the array System.out.println("the given array is "); for (int i = 0; i < lengtharr; i++) { System.out.print(arr[i] + "\t"); } for (int i = 0; i < lengtharr; i++) { if(arr[i]>lagest) { secondlargest=lagest; lagest=arr[i]; }else if(arr[i]>secondlargest) { secondlargest=arr[i]; } } return secondlargest; }
Premji
         Pradeep have given good solution. It will work forever.
Badal
         Pradeep this code will fail when int arr[]= {-5, -7, -9} values will be passed to the secondLargestElement();
shaan rizvi
         class secondLargest { public static void main(String args[]) { int[] second=new int[7]; int[] arr={15,34,12,45,67,98,67,2}; int largest=arr[0]; int j=0; for(int i=1;ilargest) { largest=arr[i]; } else { second[j]=arr[i]; j++; } } System.out.println("first largest is "+largest); int secondL=second[0]; for(int k=1;k susanta send
         public static void main(String[] args) { //int numList[] = { 21, 12, 31, 13, 41, 14 }; //int numList[] = { 112,234,34324,191,408,131,507,809 , 0}; int numList[] = { 5,4,3,2,1,0}; int maxElement = 0; int secondHighestElement = 0; for (int arrElments : numList) { if (arrElments > maxElement) { secondHighestElement = maxElement; maxElement = arrElments; }else if(secondHighestElement < arrElments){ secondHighestElement = arrElments; } } System.out.println("maxElement ::" + maxElement); System.out.println("2ndMaxElement ::" + secondHighestElement);
susanta send
         This Logic is for sorting arrary in ascending order :- I am requesting you people to go through it and let me know if you have any concern .:::: Here is the Code :- ---------------------- public static void sortArrayElement() { // Sorting IntegerArray int numList[] = { 21, 12, -31, 13, 41, -14 }; int maxElement = 0; int interchangeElement = 0; for (int i = 0; i < numList.length; ++i) { for (int j = i + 1; j <= numList.length-1; ++j) { if (numList[i] > numList[j]) { interchangeElement = numList[i]; numList[i] = numList[j]; numList[j] = interchangeElement; } } } System.out.println("sortedArray :: "); //System.out.println("2ndMaxElement ::" +numList[numList.length-2]); for(int arraryElement:numList){ System.out.println(arraryElement); } }
Aditya
         I have the below solution working at O(n)... No need to sort the array int[] input = {5,4,3,2,1}; int firstLargest = 0; int secondLargest = 0; for(int i: input){ if(i>firstLargest){ secondLargest = firstLargest; firstLargest = i; } else if(i>secondLargest){ secondLargest = i; } } System.out.println(firstLargest + "-" + secondLargest);
Naveen
         In this program largest number is showing correctly, vut secind largest is always showing first element of array.. Please suggest other logic
coder
         package secondlargest; public class secondlargest { public static void main(String[] args) { // TODO Auto-generated method stub int [] array = {15,6,1,8,9,7,4,3}; int largest; int secondlargest; if(array[0]>array[1]) { largest = array[0]; secondlargest = array[1]; } else { largest = array[1]; secondlargest = array[0]; } for(int i=2;ilargest) { secondlargest = largest; largest = array[i]; } else if((array[i]secondlargest)) { secondlargest=array[i]; } } System.out.println("second largest is = " + secondlargest); } }
Siva
         public static void Second_Max_number(){ int i =0; int a[] = {2,6,7,5,4,3}; Arrays.sort(a); int M = 0; for(i=0; iM){ M= a[i]; } } System.out.println(a[i]); System.out.println("Second Max Number"+ M); }
Shekhar
         public class SecondHighestNumber { public static void main(String a[]){ int num[] = {45,35,78,2,35,1,78,25}; SecondHighestNumber tmn = new SecondHighestNumber(); tmn.printSecondHighestNumber(num); } public void printSecondHighestNumber(int[] numbers) { int max1 = Integer.MIN_VALUE; int max2 = Integer.MIN_VALUE; for (int number : numbers) { if (number > max1) { max2 = max1; max1 = number; } else if (number > max2 && number!=max1) { max2 = number; } } System.out.println("second highest number="+max2); } }
ram
         if you are taking first element large in complete series like int arr[] = { 98, 46, 47, 86, 92, 52, 48, 36, 66, 85 } then it always return first element [like here 98 ].that is wrong .
Rajkumar Singh
         import java.util.Arrays; public class SecondLargest { public static void main(String[] args) { int[] arr = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 }; Arrays.sort(arr); int count=0; for (int i = arr.length-1; i >=0; i--) { if(count==1){ System.out.println(arr[i]); break; }else{ count++; } } } }
Rahul Chauhan
         public void findMax(int a[]){ int large = a[0]; int secondLast = a[0]; for(int i = 1 ; i < a.length ; i++){ if(large < a[i]){ secondLast = large; large = a[i]; } else if(a[i] > secondLast){ secondLast = a[i]; } else if(large == secondLast){ secondLast = a[i]; } } System.out.println("Large number "+large+" Second Last number "+secondLast); }
Rohin
         How will the program work if all the numbers entered in the array are equal
Vivekanand Chaturvedi
         int [] arr= {200,3,7,98,45,99,100,2,33,58,1,90,6,101}; Even when largest and 2nd largeset initialized with 0. Output is: largest: 200 2nd largest;0;
Dheeraj
         import java.lang.Math; // headers MUST be above the first class // one class needs to have a main() method public class HelloWorld { // arguments are passed using the text field below this editor public static void main(String[] args) { int[] var={-11,11,-11,11,11,11,-9}; int largest = 0; int secLargest = 0; if(var.length == 1) { largest = var[0]; secLargest = var[0]; } else if(var.length > 1){ largest= var[0]; secLargest = var[1]; for(int i=1;ilargest) { secLargest = largest; largest = var[i]; } else if(var[i]>secLargest && var[i] != largest) { secLargest= var[i]; } } else{ if(var[i]>largest) { secLargest = largest; largest = var[i]; } else { secLargest = var[i]; } } } } System.out.println("Largest: "+largest+" Second Largest: "+secLargest); } }
Devansh
          public static void main(String[] args) { int arr[] = { -5, 4, 3, 2, 1}; int largest = arr[0]; int secondLargest = arr[1]; System.out.println("The given array is:" ); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+"\t"); } for (int i = 1; i < arr.length; i++) { if (arr[i] > largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] > secondLargest) { secondLargest = arr[i]; } } System.out.println("\nSecond largest number is:" + secondLargest); } }
SHRIDHAR M PATIL
         package com.shree.basicprograms; import java.awt.DisplayMode; import java.util.Scanner; public class ArrayClass { public static int[] readArray() { Scanner sc = new Scanner(System.in); System.out.println("Enter the Size of array"); int n = sc.nextInt(); System.out.println("Enter " + n + " Elements"); int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = sc.nextInt(); } return ar; } public static void display(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } public static void main(String[] args) { int[] a=readArray(); display(a); int fbig=a[0],sbig=a[1]; for (int i = 1; i < a.length; i++) { if(a[i]>fbig) { sbig=fbig; fbig=a[i]; } else if(a[i]>sbig) { sbig=a[i]; } } System.out.println("First big "+fbig); System.out.println("Second big "+sbig); } }
PHANEENDRA HN
         above program(first solution) will work fine for all the scenarios, but largest and second largest needs to be initialized to smallest value of integer.
shivaraj MC
         int largest = 0; int secondLargest = 0;
shivaraj MC
         working fine.... public class A { public static void main(String[] args) { int arr[] = { -100,89,14, 46, 47, 86, 92, 52, 48, 36, 66, 85 }; int largest = 0; int secondLargest = 0; System.out.println("The given array is:" ); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+"\t"); } for (int i = 0; i < arr.length; i++) { if (arr[i] > largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] > secondLargest) { secondLargest = arr[i]; } } System.out.println("\nSecond largest number is:" + secondLargest); System.out.println(largest); } }
bharat kumar
         it not giving the correct answer in the case of, if in the zero index contains largest no, use lagest=0; // in place of lagest=arr[0] secondlargest=0; // in place of secondlagest=arr[0]
Bhanu
         None of above will work if you take all numbers as negative. Result will say that second highest is 0 as all negative numbers will be less than 0 so niether 'if' nor 'else' will be executed.. Simplest solution is at 'else' condition on line 21, use : else if (arr[i] > secondLargest || secondLargest == largest)

©candidjava.com