1.2k views
3 votes
Given two ArrayLists of sorted strings (alphabetically ascending), write down a method to merge these sorted strings’ ArrayLists into a single sorted ArrayList. The signature of the method is given below: public static ArrayList mergeList(ArrayList lst1, ArrayList lst2) Write down a test method that tests the above method. As an example if: List1 has its elements: "Austin" "Dallas" "San Francisco" and List2 has its elements : "Boston" "Chicago" "Denver" "Seattle" then the merged sorted list should have the elements in the following order : "Austin" "Boston" "Chicago", "Dallas" "Denver" "San Francisco" "Seattle"

1 Answer

1 vote

Answer:

see explaination

Step-by-step explanation:

import java.util.ArrayList;

import java.util.Arrays;

public class Merge {

public static ArrayList<String> mergeList(ArrayList<String> lst1, ArrayList<String> lst2) {

ArrayList<String> result = new ArrayList<String>();

int i = 0, j = 0;

while (i < lst1.size() || j < lst2.size()) {

if (i < lst1.size() && (j >= lst2.size() || lst1.get(i).compareTo(lst2.get(j)) < 0)) {

result.add(lst1.get(i++));

} else {

result.add(lst2.get(j++));

}

}

return result;

}

public static void main(String[] args) {

ArrayList<String> lst1 = new ArrayList<>(Arrays.asList("Austin", "Dallas", "San Fransisco"));

ArrayList<String> lst2 = new ArrayList<>(Arrays.asList("Boston", "Chicago", "Denver", "Seattle"));

System.out.println(mergeList(lst1, lst2));

}

}

User Hfs
by
4.9k points