How to find Second Highest element in Array in Java
- Three ways to find Second largest element in Array.
- using single for loop
- using Arrays.
- using Collections.
- Example :
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | package JavaPractice; import java.util.*; import java.util.stream.Collectors; public class SecondLargestNumber { /** * Using Single For loop */ public static void secondLargestNumberUsingSingleForLoop(int arr[], int arr_size) { int first, second; if (arr_size < 2) { System.out.print(" Invalid Input "); return; } first = second = Integer.MIN_VALUE; for (int i = 0; i < arr_size; i++) { if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second && arr[i] != first) { second = arr[i]; } } if (second == Integer.MIN_VALUE) System.out.print("There is no second largest" + " element\n"); else System.out.print("The second largest element" + " is " + second + "\n"); } /** * Using Arrays */ public static void secondLargestNumberUsingArrays(int arr[], int arr_size) { Arrays.sort(arr); System.out.print("The second largest element" + " is " + arr[arr_size - 2] + "\n"); } /** * Using Collections and Stream */ public static void secondLargestNumberUsingCollections(int arr[], int arr_size) { List<Integer> list = Arrays.stream(arr).boxed() .collect(Collectors.toList()); Collections.sort(list); System.out.print("The second largest element" + " is " + list.get(arr_size - 2)+ "\n"); } /** * Main Function */ public static void main(String[] args) { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = arr.length; secondLargestNumberUsingSingleForLoop(arr, n); secondLargestNumberUsingArrays(arr, n); secondLargestNumberUsingCollections(arr, n); } } |
No comments:
Post a Comment