Reputation: 35
I had a homework problem a while back that I am currently using to study for my final. Here is the question:
Write a static method named mergeSortedLists that takes two ArrayLists of Integers
that are in increasing order and returns a new ArrayList of Integers that contains the
elements of the original lists "merged" together in increasing order. For example, if the
first list contains the elements [1, 4, 4, 7, 22] and the second list is
[3, 3, 5, 5, 21, 25, 30] then the new list should be
[1, 3, 3, 4, 4, 5, 5, 7, 21, 22, 25, 30].
Again, if one list is longer than the other append the remaining elements to the end of
the new list.
My code for this problem only worked for the exact numbers given, and only if list 2 was longer than list 1. I cannot figure out how to make it work if list 1 is longer.
Here is my code:
private static ArrayList<Integer> mergeLists(ArrayList<Integer> list1, ArrayList<Integer> list2){
ArrayList<Integer> out = new ArrayList<Integer>();
int count1 = 0;
int count2 = 0;
if (list1.size() < list2.size())
{
while(count2 < list1.size())
{
if (count2 < list1.size() && list1.get(count1) < list2.get(count2))
{
out.add(list1.get(count1));
count1++;
}
else if (count2 < list1.size() && list1.get(count1) > list2.get(count2))
{
out.add(list2.get(count2));
count2++;
}
}
}
while (count1 < list1.size() || count2 < list2.size())
{
if (count1 < list1.size())
{
out.add(list1.get(count1));
count1++;
}
else if (count2 <= list2.size())
{
out.add(list2.get(count2));
count2++;
}
}
return out;
}
Upvotes: 0
Views: 1512
Reputation: 135992
I would do it differently
static List<Integer> mergeLists(List<Integer> list1, List<Integer> list2) {
List<Integer> out = new ArrayList<Integer>();
Iterator<Integer> i1 = list1.iterator();
Iterator<Integer> i2 = list2.iterator();
Integer e1 = i1.hasNext() ? i1.next() : null;
Integer e2 = i2.hasNext() ? i2.next() : null;
while (e1 != null || e2 != null) {
if (e2 == null || e1 != null && e1 < e2) {
out.add(e1);
e1 = i1.hasNext() ? i1.next() : null;
} else {
out.add(e2);
e2 = i2.hasNext() ? i2.next() : null;
}
}
return out;
}
Upvotes: 0