Merge pull request #8240 from vimde/master
BAEL-3399: How to merge two sorted arrays into a sorted array
This commit is contained in:
commit
4f78b24b1d
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.algorithms.mergesortedarrays;
|
||||
|
||||
public class SortedArrays {
|
||||
|
||||
public static int[] merge(int[] foo, int[] bar) {
|
||||
|
||||
int fooLength = foo.length;
|
||||
int barLength = bar.length;
|
||||
|
||||
int[] merged = new int[fooLength + barLength];
|
||||
|
||||
int fooPosition, barPosition, mergedPosition;
|
||||
fooPosition = barPosition = mergedPosition = 0;
|
||||
|
||||
while (fooPosition < fooLength && barPosition < barLength) {
|
||||
if (foo[fooPosition] < bar[barPosition]) {
|
||||
merged[mergedPosition++] = foo[fooPosition++];
|
||||
} else {
|
||||
merged[mergedPosition++] = bar[barPosition++];
|
||||
}
|
||||
}
|
||||
|
||||
while (fooPosition < fooLength) {
|
||||
merged[mergedPosition++] = foo[fooPosition++];
|
||||
}
|
||||
|
||||
while (barPosition < barLength) {
|
||||
merged[mergedPosition++] = bar[barPosition++];
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.algorithms.mergesortedarrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.algorithms.mergesortedarrays.SortedArrays;
|
||||
|
||||
public class SortedArraysUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
|
||||
|
||||
int[] foo = { 3, 7 };
|
||||
int[] bar = { 4, 8, 11 };
|
||||
int[] merged = { 3, 4, 7, 8, 11 };
|
||||
|
||||
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
|
||||
|
||||
int[] foo = { 3, 3, 7 };
|
||||
int[] bar = { 4, 8, 8, 11 };
|
||||
int[] merged = { 3, 3, 4, 7, 8, 8, 11 };
|
||||
|
||||
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue