diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/sortedarrays/SortedArrays.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/sortedarrays/SortedArrays.java new file mode 100644 index 0000000000..286eaae243 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/sortedarrays/SortedArrays.java @@ -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; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/sortedarrays/SortedArraysUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/sortedarrays/SortedArraysUnitTest.java new file mode 100644 index 0000000000..e5f7c3a3a5 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/sortedarrays/SortedArraysUnitTest.java @@ -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)); + } +}