Repository: TheAlgorithms/Java
Pull request #5837 (2024-10-15 06:56:53)

feat: Add `MedianFinder` new algorithm with Junit tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5837?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `80.00000%` with `3 lines` in your changes missing coverage. Please review.
> Project coverage is 66.01%. Comparing base [(`30504c1`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/30504c179ebc42d15c7b738435a87a3d8bc4053b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`40d094f`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/40d094f1f038a9d64814b71c58948851d146068f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5837?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ealgorithms/datastructures/heaps/MedianFinder.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5837?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdatastructures%2Fheaps%2FMedianFinder.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9kYXRhc3RydWN0dXJlcy9oZWFwcy9NZWRpYW5GaW5kZXIuamF2YQ==) | 80.00% | [1 Missing and 2 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5837?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5837      +/-   ##
============================================
+ Coverage     65.99%   66.01%   +0.01%     
- Complexity     4395     4403       +8     
============================================
  Files           603      604       +1     
  Lines         16799    16814      +15     
  Branches       3226     3228       +2     
============================================
+ Hits          11086    11099      +13     
- Misses         5266     5267       +1     
- Partials        447      448       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5837?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index a5d3a1a2..15f91de1 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -177,6 +177,7 @@
               * [KthElementFinder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java)
               * [LeftistHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java)
               * [MaxHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java)
+              * [MedianFinder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java)
               * [MinHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java)
               * [MinPriorityQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java)
             * lists
@@ -851,6 +852,7 @@
               * [GenericHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java)
               * [KthElementFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/KthElementFinderTest.java)
               * [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java)
+              * [MedianFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java)
               * [MinPriorityQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java)
             * lists
               * [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java)
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java
new file mode 100644
index 00000000..4e74aaec
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java
@@ -0,0 +1,59 @@
+package com.thealgorithms.datastructures.heaps;
+
+import java.util.PriorityQueue;
+
+/**
+ * This class maintains the median of a dynamically changing data stream using
+ * two heaps: a max-heap and a min-heap. The max-heap stores the smaller half
+ * of the numbers, and the min-heap stores the larger half.
+ * This data structure ensures that retrieving the median is efficient.
+ *
+ * Time Complexity:
+ * - Adding a number: O(log n) due to heap insertion.
+ * - Finding the median: O(1).
+ *
+ * Space Complexity: O(n), where n is the total number of elements added.
+ *
+ * @author Hardvan
+ */
+public final class MedianFinder {
+    MedianFinder() {
+    }
+
+    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
+    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
+
+    /**
+     * Adds a new number to the data stream. The number is placed in the appropriate
+     * heap to maintain the balance between the two heaps.
+     *
+     * @param num the number to be added to the data stream
+     */
+    public void addNum(int num) {
+        if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
+            maxHeap.offer(num);
+        } else {
+            minHeap.offer(num);
+        }
+
+        if (maxHeap.size() > minHeap.size() + 1) {
+            minHeap.offer(maxHeap.poll());
+        } else if (minHeap.size() > maxHeap.size()) {
+            maxHeap.offer(minHeap.poll());
+        }
+    }
+
+    /**
+     * Finds the median of the numbers added so far. If the total number of elements
+     * is even, the median is the average of the two middle elements. If odd, the
+     * median is the middle element from the max-heap.
+     *
+     * @return the median of the numbers in the data stream
+     */
+    public double findMedian() {
+        if (maxHeap.size() == minHeap.size()) {
+            return (maxHeap.peek() + minHeap.peek()) / 2.0;
+        }
+        return maxHeap.peek();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java
new file mode 100644
index 00000000..fcacb21f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java
@@ -0,0 +1,17 @@
+package com.thealgorithms.datastructures.heaps;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class MedianFinderTest {
+    @Test
+    public void testMedianMaintenance() {
+        MedianFinder mf = new MedianFinder();
+        mf.addNum(1);
+        mf.addNum(2);
+        assertEquals(1.5, mf.findMedian());
+        mf.addNum(3);
+        assertEquals(2.0, mf.findMedian());
+    }
+}