BAEL-3399: How to merge two sorted arrays into a sorted array

This commit is contained in:
Vivek Balasubramaniam 2019-11-24 15:19:28 +05:30
parent b9e46ff27a
commit 2f020d30ba
2 changed files with 61 additions and 0 deletions

View 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;
}
}

View 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));
}
}