Java Online Compiler
Example: FindSecondSmallest_TwoPass in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallest_TwoPass public class Main { public static int findSecondSmallestTwoPass(int[] arr) { if (arr == null || arr.length < 2) { System.out.println("Array must contain at least two elements."); return -1; } // Step 1: Find the smallest element int smallest = Integer.MAX_VALUE; for (int num : arr) { if (num < smallest) { smallest = num; } } // Step 2: Find the second smallest element // Initialize secondSmallest to MAX_VALUE to ensure any valid number will be smaller int secondSmallest = Integer.MAX_VALUE; for (int num : arr) { // If the current number is smaller than secondSmallest // AND it's not equal to the smallest element found in Step 1 if (num < secondSmallest && num != smallest) { secondSmallest = num; } } // If secondSmallest is still Integer.MAX_VALUE, it means either // all elements are the same as 'smallest', or there was no distinct second smallest. if (secondSmallest == Integer.MAX_VALUE) { System.out.println("No distinct second smallest element found."); return -1; } return secondSmallest; } public static void main(String[] args) { int[] arr1 = {12, 5, 2, 10, 8, 2, 1}; System.out.println("Original array: " + java.util.Arrays.toString(arr1)); System.out.println("Second smallest element (Two Pass): " + findSecondSmallestTwoPass(arr1)); // Output: 5 int[] arr2 = {7, 7, 3, 3, 5}; System.out.println("Original array: " + java.util.Arrays.toString(arr2)); System.out.println("Second smallest element (Two Pass): " + findSecondSmallestTwoPass(arr2)); // Output: 5 int[] arr3 = {10, 10, 10, 10}; System.out.println("Original array: " + java.util.Arrays.toString(arr3)); System.out.println("Second smallest element (Two Pass): " + findSecondSmallestTwoPass(arr3)); // Output: -1 int[] arr4 = {5}; System.out.println("Original array: " + java.util.Arrays.toString(arr4)); System.out.println("Second smallest element (Two Pass): " + findSecondSmallestTwoPass(arr4)); // Output: -1 } }
Output
Clear
ADVERTISEMENTS