Repository: TheAlgorithms/Java
Pull request #5838 (2024-10-15 07:03:21)

feat: Add `MergeKSortedArrays` 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/5838?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> 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 [(`e2c1515`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/e2c1515ef87e094122b74aa743f8ad3919925bc2?dropdown=coverage&el=desc&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    #5838      +/-   ##
============================================
+ Coverage     65.99%   66.01%   +0.02%     
- Complexity     4395     4396       +1     
============================================
  Files           603      604       +1     
  Lines         16799    16814      +15     
  Branches       3226     3230       +4     
============================================
+ Hits          11086    11100      +14     
- Misses         5266     5267       +1     
  Partials        447      447              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5838?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 bad138b3..28bd525b 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -179,6 +179,7 @@
               * [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)
+              * [MergeKSortedArrays](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.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
@@ -860,6 +861,7 @@
               * [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)
+              * [MergeKSortedArraysTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.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/MergeKSortedArrays.java b/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java
new file mode 100644
index 00000000..e41711f0
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java
@@ -0,0 +1,60 @@
+package com.thealgorithms.datastructures.heaps;
+
+import java.util.Comparator;
+import java.util.PriorityQueue;
+
+/**
+ * This class provides a method to merge multiple sorted arrays into a single sorted array.
+ * It utilizes a min-heap to efficiently retrieve the smallest elements from each array.
+ *
+ * Time Complexity: O(n * log k), where n is the total number of elements across all arrays
+ * and k is the number of arrays.
+ *
+ * Space Complexity: O(k) for the heap, where k is the number of arrays.
+ *
+ * @author Hardvan
+ */
+public final class MergeKSortedArrays {
+    private MergeKSortedArrays() {
+    }
+
+    /**
+     * Merges k sorted arrays into one sorted array using a min-heap.
+     * Steps:
+     * 1. Create a min-heap to store elements in the format: {value, array index, element index}
+     * 2. Add the first element from each array to the heap
+     * 3. While the heap is not empty, remove the smallest element from the heap
+     *   and add it to the result array. If there are more elements in the same array,
+     *   add the next element to the heap.
+     *   Continue until all elements have been processed.
+     *   The result array will contain all elements in sorted order.
+     * 4. Return the result array.
+     *
+     * @param arrays a 2D array, where each subarray is sorted in non-decreasing order
+     * @return a single sorted array containing all elements from the input arrays
+     */
+    public static int[] mergeKArrays(int[][] arrays) {
+        PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
+
+        int totalLength = 0;
+        for (int i = 0; i < arrays.length; i++) {
+            if (arrays[i].length > 0) {
+                minHeap.offer(new int[] {arrays[i][0], i, 0});
+                totalLength += arrays[i].length;
+            }
+        }
+
+        int[] result = new int[totalLength];
+        int index = 0;
+        while (!minHeap.isEmpty()) {
+            int[] top = minHeap.poll();
+            result[index++] = top[0];
+
+            if (top[2] + 1 < arrays[top[1]].length) {
+                minHeap.offer(new int[] {arrays[top[1]][top[2] + 1], top[1], top[2] + 1});
+            }
+        }
+
+        return result;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java
new file mode 100644
index 00000000..c9b75461
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java
@@ -0,0 +1,41 @@
+package com.thealgorithms.datastructures.heaps;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class MergeKSortedArraysTest {
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void testMergeKArrays(int[][] arrays, int[] expected) {
+        assertArrayEquals(expected, MergeKSortedArrays.mergeKArrays(arrays));
+    }
+
+    private static Stream<Arguments> provideTestCases() {
+        return Stream.of(
+            // Basic test case with multiple arrays
+            Arguments.of(new int[][] {{1, 4, 5}, {1, 3, 4}, {2, 6}}, new int[] {1, 1, 2, 3, 4, 4, 5, 6}),
+
+            // Edge case: All arrays are empty
+            Arguments.of(new int[][] {{}, {}, {}}, new int[] {}),
+
+            // Edge case: One array is empty
+            Arguments.of(new int[][] {{1, 3, 5}, {}, {2, 4, 6}}, new int[] {1, 2, 3, 4, 5, 6}),
+
+            // Single array
+            Arguments.of(new int[][] {{1, 2, 3}}, new int[] {1, 2, 3}),
+
+            // Arrays with negative numbers
+            Arguments.of(new int[][] {{-5, 1, 3}, {-10, 0, 2}}, new int[] {-10, -5, 0, 1, 2, 3}),
+
+            // Arrays with duplicate elements
+            Arguments.of(new int[][] {{1, 1, 2}, {1, 3, 3}, {2, 2, 4}}, new int[] {1, 1, 1, 2, 2, 2, 3, 3, 4}),
+
+            // Edge case: Arrays of varying lengths
+            Arguments.of(new int[][] {{1, 2}, {3}, {4, 5, 6, 7}}, new int[] {1, 2, 3, 4, 5, 6, 7}));
+    }
+}