Java Online Compiler
Example: FindSecondSmallestAndLargest_SinglePass in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindSecondSmallestAndLargest_SinglePass 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; } // Step 2: Initialize variables for smallest and largest elements int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; // Step 3: Iterate through the array once for (int num : arr) { // Logic for smallest and second smallest if (num < smallest) { secondSmallest = smallest; // Current smallest becomes second smallest smallest = num; // Current num becomes new smallest } else if (num < secondSmallest && num != smallest) { secondSmallest = num; // Update second smallest if num is between smallest and secondSmallest } // Logic for largest and second largest if (num > largest) { secondLargest = largest; // Current largest becomes second largest largest = num; // Current num becomes new largest } else if (num > secondLargest && num != largest) { secondLargest = num; // Update second largest if num is between largest and secondLargest } } // Step 4: 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