Skip to content

Commit 28a32ae

Browse files
TINOTINO
authored andcommitted
BAEL-3482
Code re-factor
1 parent b5f9e1f commit 28a32ae

4 files changed

Lines changed: 49 additions & 79 deletions

File tree

algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeap.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,31 @@ void swap(int i, int j) {
5858
heapNodes[i] = heapNodes[j];
5959
heapNodes[j] = temp;
6060
}
61+
62+
static int[] merge(int[][] array) {
63+
HeapNode[] heapNodes = new HeapNode[array.length];
64+
int resultingArraySize = 0;
65+
66+
for (int i = 0; i < array.length; i++) {
67+
HeapNode node = new HeapNode(array[i][0], i);
68+
heapNodes[i] = node;
69+
resultingArraySize += array[i].length;
70+
}
71+
72+
MinHeap minHeap = new MinHeap(heapNodes);
73+
int[] resultingArray = new int[resultingArraySize];
74+
75+
for (int i = 0; i < resultingArraySize; i++) {
76+
HeapNode root = minHeap.getRootNode();
77+
resultingArray[i] = root.element;
78+
79+
if (root.nextElementIndex < array[root.arrayIndex].length) {
80+
root.element = array[root.arrayIndex][root.nextElementIndex++];
81+
} else {
82+
root.element = Integer.MAX_VALUE;
83+
}
84+
minHeap.heapifyFromRoot();
85+
}
86+
return resultingArray;
87+
}
6188
}

algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/minheapmerge/MinHeapMerge.java

Lines changed: 0 additions & 40 deletions
This file was deleted.

algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapMergeUnitTest.java

Lines changed: 0 additions & 39 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.algorithms.minheapmerge;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.CoreMatchers.is;
5+
import static org.junit.Assert.assertThat;
6+
7+
import org.junit.Test;
8+
9+
public class MinHeapUnitTest {
10+
11+
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
12+
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
13+
14+
@Test
15+
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
16+
int[] resultArray = MinHeap.merge(inputArray);
17+
18+
assertThat(resultArray.length, is(equalTo(10)));
19+
assertThat(resultArray, is(equalTo(expectedArray)));
20+
}
21+
22+
}

0 commit comments

Comments
 (0)