Java Online Compiler
Example: FindNthElementsUsingSorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindNthElementsUsingSorting import java.util.Arrays; import java.util.OptionalInt; public class Main { public static void main(String[] args) { int[] numbers = {10, 5, 20, 8, 15, 20, 12, 5}; System.out.println("Original array: " + Arrays.toString(numbers)); // Step 1: Handle edge cases for array size if (numbers.length < 2) { System.out.println("Array must have at least 2 elements to find second smallest."); return; } if (numbers.length < 3) { System.out.println("Array must have at least 3 elements to find third largest."); return; } // Step 2: Sort the array Arrays.sort(numbers); System.out.println("Sorted array: " + Arrays.toString(numbers)); // Step 3: Find the second smallest element // After sorting, the second smallest element is at index 1 int secondSmallest = numbers[1]; // Step 4: Find the third largest element // After sorting, the third largest element is at index length - 3 int thirdLargest = numbers[numbers.length - 3]; System.out.println("Second Smallest Element: " + secondSmallest); System.out.println("Third Largest Element: " + thirdLargest); } }
Output
Clear
ADVERTISEMENTS