Write a Java application containing the method that merges two arrays, alternati
ID: 3930102 • Letter: W
Question
Write a Java application containing the method that merges two arrays, alternating elements from both arrays. If one array is shorter than the other one, then alternate as long as you can and then append the remaining elements from the longer array in their order. For example, if a = {1 4 9 16} b = {9 7 4 9 11 20 5} then merge returns the array 1 9 4 7 9 4 16 9 11 20 5 Initialize both arrays In your code (at least 5 elements in each array). You should not assume that the second array is always longer. Your program should display the original arrays and the merged array on the screen.Explanation / Answer
public static ArrayList merge(ArrayList a, ArrayList b) {
int c1 = 0, c2 = 0;
ArrayList<Integer> res = new ArrayList<Integer>();
while(c1 < a.size() || c2 < b.size()) {
if(c1 < a.size())
res.add((Integer) a.get(c1++));
if(c2 < b.size())
res.add((Integer) b.get(c2++));
}
return res;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.