Java Online Compiler
Example: FindSecondSmallestAndLargest_Sorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallestAndLargest_Sorting import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {10, 5, 20, 15, 25, 5}; // Example array with duplicates // Step 1: Handle edge cases for arrays with less than 2 elements if (arr.length < 2) { System.out.println("Array must contain at least two elements."); return; } // Step 2: Sort the array in ascending order Arrays.sort(arr); // Step 3: Find the second smallest element // Iterate to find the first element different from the smallest int smallest = arr[0]; int secondSmallest = Integer.MAX_VALUE; // Initialize with max value for (int i = 1; i < arr.length; i++) { if (arr[i] > smallest) { secondSmallest = arr[i]; break; // Found the second distinct smallest } } // Step 4: Find the second largest element // Iterate backwards to find the first element different from the largest int largest = arr[arr.length - 1]; int secondLargest = Integer.MIN_VALUE; // Initialize with min value for (int i = arr.length - 2; i >= 0; i--) { if (arr[i] < largest) { secondLargest = arr[i]; break; // Found the second distinct largest } } // Step 5: Print the results, checking if distinct elements were found if (secondSmallest == Integer.MAX_VALUE) { System.out.println("No distinct second smallest element found."); } else { System.out.println("Second Smallest: " + secondSmallest); } if (secondLargest == Integer.MIN_VALUE) { System.out.println("No distinct second largest element found."); } else { System.out.println("Second Largest: " + secondLargest); } } }
Output
Clear
ADVERTISEMENTS