Java Online Compiler
Example: FindSecondSmallest_Sorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallest_Sorting import java.util.Arrays; public class Main { public static int findSecondSmallestUsingSort(int[] arr) { if (arr == null || arr.length < 2) { System.out.println("Array must contain at least two elements."); return -1; // Indicate error or invalid input } // Step 1: Sort the array Arrays.sort(arr); // Step 2: Iterate to find the second distinct smallest element // The smallest element is at arr[0]. // We look for the first element greater than arr[0]. for (int i = 1; i < arr.length; i++) { if (arr[i] > arr[0]) { return arr[i]; // This is the second smallest distinct element } } // If all elements are the same (e.g., [5, 5, 5]), // there is no distinct second smallest element. System.out.println("No distinct second smallest element found."); return -1; } public static void main(String[] args) { int[] arr1 = {12, 5, 2, 10, 8, 2, 1}; System.out.println("Original array: " + Arrays.toString(arr1)); System.out.println("Second smallest element (Sorting): " + findSecondSmallestUsingSort(arr1)); // Output: 5 int[] arr2 = {7, 7, 3, 3, 5}; System.out.println("Original array: " + Arrays.toString(arr2)); System.out.println("Second smallest element (Sorting): " + findSecondSmallestUsingSort(arr2)); // Output: 5 int[] arr3 = {10, 10, 10, 10}; System.out.println("Original array: " + Arrays.toString(arr3)); System.out.println("Second smallest element (Sorting): " + findSecondSmallestUsingSort(arr3)); // Output: -1 int[] arr4 = {5}; System.out.println("Original array: " + Arrays.toString(arr4)); System.out.println("Second smallest element (Sorting): " + findSecondSmallestUsingSort(arr4)); // Output: -1 } }
Output
Clear
ADVERTISEMENTS