Skip to content

Commit 5ef4c96

Browse files
committed
feat: Add KthElementFinder new algorithm with Junit tests
1 parent 30504c1 commit 5ef4c96

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.datastructures.heaps;
2+
3+
import java.util.PriorityQueue;
4+
5+
public class KthElementFinder {
6+
public static int findKthLargest(int[] nums, int k) {
7+
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
8+
for (int num : nums) {
9+
minHeap.offer(num);
10+
if (minHeap.size() > k) {
11+
minHeap.poll();
12+
}
13+
}
14+
return minHeap.peek();
15+
}
16+
17+
public static int findKthSmallest(int[] nums, int k) {
18+
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
19+
for (int num : nums) {
20+
maxHeap.offer(num);
21+
if (maxHeap.size() > k) {
22+
maxHeap.poll();
23+
}
24+
}
25+
return maxHeap.peek();
26+
}
27+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.thealgorithms.datastructures.heaps;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class KthElementFinderTest {
8+
@Test
9+
public void testFindKthLargest() {
10+
int[] nums = {3, 2, 1, 5, 6, 4};
11+
assertEquals(5, KthElementFinder.findKthLargest(nums, 2));
12+
}
13+
14+
@Test
15+
public void testFindKthSmallest() {
16+
int[] nums = {7, 10, 4, 3, 20, 15};
17+
assertEquals(7, KthElementFinder.findKthSmallest(nums, 3));
18+
}
19+
}

0 commit comments

Comments
 (0)