public class MergeArrays {
public static void main(String args[]) {
int[] a1 = new int[] { 1, 3, 5, 7, 9,23 };
int[] a2 = new int[] { 2, 4, 6,10,21 };
int[] c = mergeArrays(a1, a2);
for (int i : c)
System.out.println(" " + i);
}
public static int[] mergeArrays(int[] a1, int[] a2) {
int len = a1.length + a2.length;
int[] newA = new int[len];
int indexA1 = 0;
int indexA2 = 0;
int indexNew = 0;
while (indexA1 < a1.length && indexA2 < a2.length) {
if (a1[indexA1] <= a2[indexA2]) {
newA[indexNew] = a1[indexA1];
indexA1++;
} else {
newA[indexNew] = a2[indexA2];
indexA2++;
}
indexNew++;
}
while(indexA1 <a1.length)
{
newA[indexNew] = a1[indexA1];
indexNew++;
indexA1++;
}
while(indexA2 <a2.length)
{
newA[indexNew] = a2[indexA2++];
indexNew++;
indexA2++;
}
return newA;
}
Comments
Post a Comment