Write a method that merges two array lists, alternating elements from both array lists
public static void main(String[] args) {
int[] first = { 1, 4, 9, 16 };
int[] second = { 9, 7, 4, 9, 11 };
int[] merge = new int[first.length + second.length];
int j = 0, k = 0, l = 0;
int max = Math.max(first.length, second.length);
for (int i = 0; i < max; i++) {
if (j < first.length)
merge[l++] = first[j++];
if (k < second.length)
merge[l++] = second[k++];
}
System.out.println(Arrays.toString(merge));
}
Output: 1 9 4 7 9 4 16 9 11
No comments:
Post a Comment