Skip to content

Commit 61ff123

Browse files
committed
feat: Add MedianFinder new algorithm with Junit tests
1 parent 30504c1 commit 61ff123

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.thealgorithms.datastructures.heaps;
2+
3+
import java.util.PriorityQueue;
4+
5+
/**
6+
* This class maintains the median of a dynamically changing data stream using
7+
* two heaps: a max-heap and a min-heap. The max-heap stores the smaller half
8+
* of the numbers, and the min-heap stores the larger half.
9+
* This data structure ensures that retrieving the median is efficient.
10+
*
11+
* Time Complexity:
12+
* - Adding a number: O(log n) due to heap insertion.
13+
* - Finding the median: O(1).
14+
*
15+
* Space Complexity: O(n), where n is the total number of elements added.
16+
*
17+
* @author Hardvan
18+
*/
19+
public final class MedianFinder {
20+
MedianFinder() {
21+
}
22+
23+
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
24+
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
25+
26+
/**
27+
* Adds a new number to the data stream. The number is placed in the appropriate
28+
* heap to maintain the balance between the two heaps.
29+
*
30+
* @param num the number to be added to the data stream
31+
*/
32+
public void addNum(int num) {
33+
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
34+
maxHeap.offer(num);
35+
} else {
36+
minHeap.offer(num);
37+
}
38+
39+
if (maxHeap.size() > minHeap.size() + 1) {
40+
minHeap.offer(maxHeap.poll());
41+
} else if (minHeap.size() > maxHeap.size()) {
42+
maxHeap.offer(minHeap.poll());
43+
}
44+
}
45+
46+
/**
47+
* Finds the median of the numbers added so far. If the total number of elements
48+
* is even, the median is the average of the two middle elements. If odd, the
49+
* median is the middle element from the max-heap.
50+
*
51+
* @return the median of the numbers in the data stream
52+
*/
53+
public double findMedian() {
54+
if (maxHeap.size() == minHeap.size()) {
55+
return (maxHeap.peek() + minHeap.peek()) / 2.0;
56+
}
57+
return maxHeap.peek();
58+
}
59+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.thealgorithms.datastructures.heaps;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class MedianFinderTest {
7+
@Test
8+
public void testMedianMaintenance() {
9+
MedianFinder mf = new MedianFinder();
10+
mf.addNum(1);
11+
mf.addNum(2);
12+
assertEquals(1.5, mf.findMedian());
13+
mf.addNum(3);
14+
assertEquals(2.0, mf.findMedian());
15+
}
16+
}

0 commit comments

Comments
 (0)