Write a static method named mergeSortedLists that takes two ArrayLists of Intege
ID: 3807125 • Letter: W
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 theend of the new list.
Explanation / Answer
I have written the program in Java using ArrayList. Below is the program
import java.util.ArrayList;
import java.util.Arrays;
public class mergeTest {
public static ArrayList<Integer> mergeSortedLists(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
ArrayList<Integer> output = new ArrayList<Integer>();
int i = 0, j = 0, k = 0;
// this loop will compare the 2 elements of different lists, and copy the smaller into output
while (i < list1.size() && j < list2.size())
{
if (list1.get(i) < list2.get(j))
{
output.add(list1.get(i));
i++;
}
else
{
output.add(list2.get(j));
j++;
}
k++;
}
// the below 2 loops copy the entire list into output once the list exhausted
while (i < list1.size())
{
output.add(list1.get(i));
i++;
k++;
}
while (j < list2.size())
{
output.add(list2.get(j));
j++;
k++;
}
return output;
}
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1, 4, 4, 7, 22));
ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(3, 3, 5, 5, 21, 25, 30));
System.out.println(" list 1 input ");
for(int item : list1)
{
System.out.println(item);
}
System.out.println(" list 2 input ");
for(int item : list2)
{
System.out.println(item);
}
ArrayList<Integer> sortedList = mergeSortedLists(list1,list2);
System.out.println("");
System.out.println("merged list after sorting");
for(int item : sortedList)
{
System.out.println(item);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.