First post.
Can you please review my code and help me improve my coding. Please also suggest improvements if there is a miss in this post.
Problem Statement
Given two sorted arrays
X[]andY[]of size m and n each, merge elements ofX[]with elements of arrayY[]by maintaining the sorted order.
i.e. fillX[]with first m smallest elements and fillY[]with remaining elements.Input:
X[] = {1, 4, 7, 8, 10} , Y[] = {2, 3, 9}Output:
X[] = {1, 2, 3, 4, 7} , Y[] = {8, 9, 10}
public static void main(String[] args) {
int[] X = {11, 14, 17, 18, 110};
int[] Y = {112, 113, 114};
mergeRunner(X, Y);
System.out.println("X: " + Arrays.toString(X));
System.out.println("Y: " + Arrays.toString(Y));
}
private static void mergeRunner(int[] x, int[] y) {
if (x[x.length - 1] > y[y.length - 1]) {
merge(x, y);
} else {
merge(y, x);
}
}
private static void merge(int[] x, int[] y) {
final int m = x.length;
final int n = y.length;
int last = x[m - 1];
int i = m - 2;
for (int j = n - 1; j >= 0; j--) {
while (i >= 0 && x[i] > y[j]) {
i--;
}
//Insertion
insertValue(x, i + 1, y[j]);
y[j] = last;
last = x[m - 1];
//System.out.println("X: " + Arrays.toString(x));
//System.out.println("Y: " + Arrays.toString(y));
}
}
private static void insertValue(int[] x, int index, int valueToInsert) {
int i = x.length - 1;
while (i > index) {
x[i] = x[i - 1];
i--;
}
x[i] = valueToInsert;
}