How will you merge two sorted arrays, when The longer array has empty spaces to accomodate the second array. Complexity: O (items in longer + items in smaller). Request for making code concise, clean and optimal.
public final class MergeArrays {
private MergeArrays() {}
private static void check(Integer[] big, Integer[] small) {
if (big == null && small == null) {
throw new NullPointerException("The input arrays are null.");
}
if (big.length < small.length) {
throw new IllegalArgumentException("The arrays is smaller smaller array");
}
}
public static Integer[] mergeSortedArrays(Integer[] big, Integer[] small) {
check(big, small);
int limit = 0;
for (Integer val : big) {
if (val == null) { break; }
limit++;
}
return mergeSortedArrays(big, limit, small);
}
private static Integer[] mergeSortedArrays(Integer[] big, int limit, Integer[] small) {
assert big != null;
assert small != null;
int limitIndex = limit - 1;
int bigIndex = big.length - 1;
int smallIndex = small.length - 1;
while (smallIndex >= 0) {
if (limitIndex < 0 || big[limitIndex] < small[smallIndex]) {
big[bigIndex--] = small[smallIndex--];
} else {
big[bigIndex--] = big[limitIndex--];
}
}
return big;
}