Finding the second largest or second smallest element in an array.
Here’s a Java program that finds the second largest and second smallest elements in an array:
import java.util.Arrays; public class SecondLargestAndSmallest { public static void main(String[] args) { int[] array = {5, 8, 2, 10, 7, 1, 6, 3, 9, 4}; int secondLargest = findSecondLargest(array); int secondSmallest = findSecondSmallest(array); System.out.println("Second largest element: " + secondLargest); System.out.println("Second smallest element: " + secondSmallest); } public static int findSecondLargest(int[] array) { int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for (int num : array) { if (num > largest) { secondLargest = largest; largest = num; } else if (num > secondLargest && num != largest) { secondLargest = num; } } return secondLargest; } public static int findSecondSmallest(int[] array) { int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; for (int num : array) { if (num < smallest) { secondSmallest = smallest; smallest = num; } else if (num < secondSmallest && num != smallest) { secondSmallest = num; } } return secondSmallest; } }
This program initializes an array with some values and then uses two separate methods, `findSecondLargest` and `findSecondSmallest`, to find the second largest and second smallest elements, respectively. The methods iterate through the array and keep track of the largest/smallest and second largest/smallest elements found so far. Finally, the program prints the results.
For example, with the given array `{5, 8, 2, 10, 7, 1, 6, 3, 9, 4}`, the program will output:
Second largest element: 9
Second smallest element: 2
Please note that the program assumes the array contains at least two distinct elements. If the array contains duplicates and you want to handle them differently, you can modify the comparison condition in the `if` statements inside the `findSecondLargest` and `findSecondSmallest` methods.