BAEL-3399: How to merge two sorted arrays into a sorted array
This commit is contained in:
parent
b9e46ff27a
commit
2f020d30ba
algorithms-miscellaneous-5/src
main/java/com/baeldung/algorithms/sortedarrays
test/java/com/baeldung/algorithms/sortedarrays
34
algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/sortedarrays/SortedArrays.java
Normal file
34
algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/sortedarrays/SortedArrays.java
Normal file
@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.sortedarrays;
|
||||
|
||||
public class SortedArrays {
|
||||
|
||||
public static int[] merge(int[] first, int[] second) {
|
||||
|
||||
int m = first.length;
|
||||
int n = second.length;
|
||||
|
||||
int i, j, k;
|
||||
i = j = k = 0;
|
||||
|
||||
int[] result = new int[m + n];
|
||||
|
||||
while (i < m && j < n) {
|
||||
|
||||
if (first[i] < second[j]) {
|
||||
result[k++] = first[i++];
|
||||
} else {
|
||||
result[k++] = second[j++];
|
||||
}
|
||||
}
|
||||
|
||||
while (i < m) {
|
||||
result[k++] = first[i++];
|
||||
}
|
||||
|
||||
while (j < n) {
|
||||
result[k++] = second[j++];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
27
algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/sortedarrays/SortedArraysUnitTest.java
Normal file
27
algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/sortedarrays/SortedArraysUnitTest.java
Normal file
@ -0,0 +1,27 @@
|
||||
package com.baeldung.algorithms.sortedarrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SortedArraysUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArraysWhenMergeThenReturnMergedSortedArray() {
|
||||
|
||||
int[] first = { 3, 7 };
|
||||
int[] second = { 4, 8, 11 };
|
||||
int[] result = { 3, 4, 7, 8, 11 };
|
||||
|
||||
assertArrayEquals(result, SortedArrays.merge(first, second));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArraysWithDuplicatesWhenMergeThenReturnMergedSortedArray() {
|
||||
|
||||
int[] first = { 3, 3, 7 };
|
||||
int[] second = { 4, 8, 8, 11 };
|
||||
int[] result = { 3, 3, 4, 7, 8, 8, 11 };
|
||||
|
||||
assertArrayEquals(result, SortedArrays.merge(first, second));
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user