-2

Write a method

public static ArrayList<Integer> merge(ArrayList<Integer> a, ArrayList<Integer> b)

that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is

1 4 9 16

and b is

9 7 4 9 11

then merge returns the array list

1 9 4 7 9 4 16 9 11
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Harrison
  • 1
  • 1

2 Answers2

1
public static ArrayList<Integer> merge(ArrayList<Integer> x,
        ArrayList<Integer> y) {
    ArrayList<Integer> temp = new ArrayList<Integer>(x.size() + y.size());
    int i = 0, j = 0;
    for (i = 0, j = 0; i < x.size() && j < y.size(); i++, j++) {
        temp.add(x.get(i));
        temp.add(y.get(j));
    }
    while (i < x.size()) {
        temp.add(x.get(i));
        i++;
    }
    while (j < y.size()) {
        temp.add(y.get(j));
        j++;
    }
    return temp;

}

Merged is [1, 9, 4, 7, 9, 4, 16, 9, 25, 11, 36, 21, 49, 64, 81]

Renuka Deshmukh
  • 998
  • 9
  • 16
0
public static ArrayList<Integer> merge(ArrayList<Integer> x, ArrayList<Integer> y)
{
    ArrayList<Integer> temp = new ArrayList<Integer>(x.size() + y.size());      
    int m  = x.size() > y.size() ? x.size() : y.size();

    for (int i = 0; i < m; i++)
    {
        if (i < x.size()) temp.add(x.get(i));
        if (i < y.size()) temp.add(y.get(i));
    }

    return temp;
}

Output:

Merged is [1, 9, 4, 7, 9, 4, 16, 9, 25, 11, 36, 21, 49, 64, 81]
Jts
  • 3,447
  • 1
  • 11
  • 14