Write a \"merge\" program IN MIPS that merges two ordered lists of integers into
ID: 3852759 • Letter: W
Question
Write a "merge" program IN MIPS that merges two ordered lists of integers into a new ordered list. For example, given two ordered lists (1,4,6,9) and (0,2,3,7) as input arguments, "merge" should produce a new list (0,1,2,3,4,6,7,9) which is also ordered. Another example could be to merge (-3,0,6) and (-2,0,4,5,9) to produce (-2,-3,0,0,4,5,6,9). The "merge" program assumes that the two input lists (in increasing order) of integers are stored in the data area. It loads the integers and merges them into an ordered list. The resulting ordered list (e.g. (-2,-3,0,0,4,5,6,9)) should be stored back into the data area. It is at your own choice how the data area (i.e. the lists) is arranged, and whether the resulting list is overwritten onto the original two lists. But be sure to give meaningful labels and clearly indicate (using label or comments) where the merged list is stored. Before your program terminates, it should print out the merged list which should be in increasing order. Hints: You may refer to wikipedia entry of Merge Algorithm for the outline of the algorithm at https://en.wikipedia.org/wiki/Merge_algorithm. Note: Please do NOT implement any sorting algorithm! You will receive a grade of zero (0) if you do so
Explanation / Answer
import java.util.*;
class merge{
// static LinkedList list1 = new LinkedList(Arrays.asList(1,4,6,9));
// static LinkedList list2 = new LinkedList(Arrays.asList(0,2,3,7));
static LinkedList list1 = new LinkedList(Arrays.asList(-3,0,6));
static LinkedList list2 = new LinkedList(Arrays.asList(-2,0,4,5,9));
static LinkedList list3 = new LinkedList();
public static void main(String[] args)
{
ListIterator<Integer> list1Iterator = list1.listIterator();
ListIterator<Integer> list2Iterator = list2.listIterator();
Integer i1 = list1Iterator.next();
Integer i2 = list2Iterator.next();
while (true) //endless, breaks when one of the list reaches its end
{
if(i1 > i2)
{
list3.add(i1);
if(list1Iterator.hasNext())
{
i1 = list1Iterator.next();
}
else //no element left in list1, fill list3 with the rest of list2 and break
{
list3.add(i2);
while(list2Iterator.hasNext())
{
list3.add(list2Iterator.next());
}
break;
}
}
else
{
list3.add(i2);
if(list2Iterator.hasNext())
{
i2 = list2Iterator.next();
}
else //no element left in list2, fill list3 with the reset of list1 and break
{
list3.add(i1);
while(list1Iterator.hasNext())
{
list3.add(listIterator.next());
}
break;
}
}
}
System.out.println(list3);
}
} //class merge
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.