write a merge method that merges two array-based sorted lists together. This sta
ID: 3741765 • Letter: W
Question
write a merge method that merges two array-based sorted lists together.
This static method is written from the implementation perspective, meaning it goes inside the SortedArrayList class.
The method should be efficient- meaning O(n).
This will require you to directly access both arrays.
This means you need to avoid the "shifting" that can occur during adds!
The method header is:
public static <U> SortedArrayList<U> createMergeList(SortedArrayList<U> listA, SortedArrayList<U> listB)
U here is the generic type. (What we usually call "T".)
You can assume U is Comparable.
Don't worry about why the generics looks a little different in this example.
(The reason it's different is because we are declaring a generic type only for the current method.)
Explanation / Answer
Hi friend, Since you have not posted SortedList so i can not test.
I have implemented after assuming some function existence.
public static <U> SortedArrayList<U> createMergeList(SortedArrayList<U> listA, SortedArrayList<U> listB) {
SortedArrayList<U> mergedList = new SortedArrayList<U>();
int i=0, j=0;
int n1 = listA.size();
int n2 = listB.size();
while(i < n1 && j < n2) {
if(listA.get(i).compareTo(listB.get(j)) <= 0) {
mergedList.add(listA.get(i));
i++;
}else{
mergedList.add(listB.get(j));
j++;
}
}
// remaining elements form A
while(i < n1) {
mergedList.add(listA.get(i));
i++;
}
// remaining elements form B
while(j < n2) {
mergedList.add(listB.get(j));
j++;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.