Java Online Compiler
Example: FindSecondSmallest_SinglePass in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallest_SinglePass public class Main { public static int findSecondSmallestSinglePass(int[] arr) { if (arr == null || arr.length < 2) { System.out.println("Array must contain at least two elements."); return -1; } // Step 1: Initialize smallest and secondSmallest // We can't use arr[0] and arr[1] directly due to potential duplicates or order. // Initialize with MAX_VALUE to ensure any array element will be smaller. int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; // Step 2: Iterate through the array once for (int num : arr) { if (num < smallest) { // If current number is smaller than smallest, // the old smallest becomes the new secondSmallest, // and the current number becomes the new smallest. secondSmallest = smallest; smallest = num; } else if (num < secondSmallest && num != smallest) { // If current number is smaller than secondSmallest // but not equal to smallest, then it's the new secondSmallest. secondSmallest = num; } } // Step 3: Check if a distinct second smallest was found 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 (Single Pass): " + findSecondSmallestSinglePass(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 (Single Pass): " + findSecondSmallestSinglePass(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 (Single Pass): " + findSecondSmallestSinglePass(arr3)); // Output: -1 int[] arr4 = {5}; System.out.println("Original array: " + java.util.Arrays.toString(arr4)); System.out.println("Second smallest element (Single Pass): " + findSecondSmallestSinglePass(arr4)); // Output: -1 } }
Output
Clear
ADVERTISEMENTS