Java Online Compiler
Example: FindKthElementSorting in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindKthElementSorting import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {7, 10, 4, 3, 20, 15}; int k = 3; System.out.println("Original Array: " + Arrays.toString(arr)); // Find Kth Smallest Element int[] arrSmallest = Arrays.copyOf(arr, arr.length); // Use a copy to preserve original Arrays.sort(arrSmallest); // Step 1: Sort the array // Step 2: Access the element at index k-1 int kthSmallest = arrSmallest[k - 1]; System.out.println(k + "th Smallest Element (via Sorting): " + kthSmallest); // Find Kth Largest Element int[] arrLargest = Arrays.copyOf(arr, arr.length); // Use a copy Arrays.sort(arrLargest); // Step 1: Sort the array // Step 2: Access the element at index n-k (where n is array length) int kthLargest = arrLargest[arrLargest.length - k]; System.out.println(k + "th Largest Element (via Sorting): " + kthLargest); } }
Output
Clear
ADVERTISEMENTS