Java Online Compiler
Example: FindSecondSmallestAndLargest_TwoPass in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallestAndLargest_TwoPass public class Main { public static void main(String[] args) { int[] arr = {10, 5, 20, 15, 25, 5}; // Example array // Step 1: Handle edge cases if (arr.length < 2) { System.out.println("Array must contain at least two elements."); return; } // --- Find Second Smallest --- // Step 2: Initialize smallest and secondSmallest int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; // Step 3: First pass to find the absolute smallest for (int num : arr) { if (num < smallest) { smallest = num; } } // Step 4: Second pass to find the second smallest // Ensure it's not the same as the smallest for (int num : arr) { if (num < secondSmallest && num != smallest) { secondSmallest = num; } } // --- Find Second Largest --- // Step 5: Initialize largest and secondLargest int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; // Step 6: First pass to find the absolute largest for (int num : arr) { if (num > largest) { largest = num; } } // Step 7: Second pass to find the second largest // Ensure it's not the same as the largest for (int num : arr) { if (num > secondLargest && num != largest) { secondLargest = num; } } // Step 8: Print the results 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