Java Online Compiler
Example: FindKthElementHeap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// FindKthElementHeap import java.util.PriorityQueue; import java.util.Collections; // For reverse order comparator 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 using a Max-Heap // A max-heap stores the 'k' largest elements seen so far. // The root will be the largest among these 'k', if current element < root, replace. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); for (int num : arr) { maxHeap.offer(num); // Add element if (maxHeap.size() > k) { maxHeap.poll(); // Remove the largest element if size exceeds k } } // Step 1: Iterate through the array. // Step 2: Add each element to a max-heap. // Step 3: If heap size exceeds k, remove the largest element (heap's root). // Step 4: The root of the max-heap after iteration will be the k-th smallest. System.out.println(k + "th Smallest Element (via Max-Heap): " + maxHeap.peek()); // Find Kth Largest Element using a Min-Heap // A min-heap stores the 'k' smallest elements seen so far. // The root will be the smallest among these 'k', if current element > root, replace. PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // Default is min-heap for (int num : arr) { minHeap.offer(num); // Add element if (minHeap.size() > k) { minHeap.poll(); // Remove the smallest element if size exceeds k } } // Step 1: Iterate through the array. // Step 2: Add each element to a min-heap. // Step 3: If heap size exceeds k, remove the smallest element (heap's root). // Step 4: The root of the min-heap after iteration will be the k-th largest. System.out.println(k + "th Largest Element (via Min-Heap): " + minHeap.peek()); } }
Output
Clear
ADVERTISEMENTS