Find Second Largest Number in Array
Here, you will know to find second largest number in array java program. We will do this program by using two different ways.
1. With Sorting Array method
2. Without Sorting Array method
Find Second Largest Number in Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import java.util.*; public class ArraySecondLargest { public static void main(String args[]) { int i,j, Largest, Smallest, tmp; Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } //sorting in assending order for (i = 0; i < arr.length; i++) { for(j = i + 1 ; j< arr.length; j++) { if(arr[i]>arr[j]) { tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; } } } // find second largest number int secondLagrest=arr[(arr.length)-2]; System.out.print("\nSecond Largest number is : "+secondLagrest); } } |
Output
Find Second Largest Number in Array without Sorting
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | //Find Second Largest Number in Array without Sorting import java.util.Scanner; public class SecondLargestWtSort { //method to find second largest number public static int findSecondLargest(int[] arr) { int largest = arr[0]; int secondLargest = arr[0]; int i = 1; while (i < arr.length) { int num = arr[i]; if (num > largest) { secondLargest = largest; largest = num; } else if (num > secondLargest && num != largest) { secondLargest = num; } i++; } return secondLargest; } public static void main(String[] args) { //int[] arr = {10, 5, 8, 20, 9}; Scanner sc = new Scanner(System.in); //Input how many elements System.out.print("Enter number of elements : "); int num=sc.nextInt(); int arr[]=new int[num]; // input Array elements System.out.print("Enter elements of array : "); for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } sc.close(); int result = findSecondLargest(arr); if (result != -1) { System.out.println("Second largest number : " + result); } } } |
Output
C:\CodeRevise\java>javac SecondLargestWtSort.java
C:\CodeRevise\java>java SecondLargestWtSort
Enter number of elements : 6
Enter elements of array : 3
5
2
9
7
4
Second largest number : 7
Check out our other Java Programming Examples