When I run this the merge sort is not happening and I can’t figure out where the problem is. int brelem and SortThread task arguments are there only because I need them to Override a method of the parent class properly so they do not play any role in this case.
class MergeSort extends Sort {
@Override
ArrayList sort(ArrayList<Integer> a, int brelem, SortThread task) {
if (a.size() > 1) {
ArrayList<Integer> firstHalf = new ArrayList<>(a.subList(0, a.size() / 2));
firstHalf.subList(0, a.size() / 2);
firstHalf=sort(firstHalf, a.size() / 2, task);
ArrayList<Integer> secondHalf = new ArrayList<>(a.subList(a.size()/2, a.size()));
secondHalf=sort(secondHalf, secondHalf.size(), task);
ArrayList<Integer> temp = merge(firstHalf, secondHalf);
a.subList(0, temp.size());
}
return a;
}
private static ArrayList merge(ArrayList<Integer> list1, ArrayList<Integer> list2) {
ArrayList<Integer> temp = new ArrayList<>();
int current1 = 0;
int current2 = 0;
int current3 = 0;
while (current1 < list1.size() && current2 < list2.size()) {
if (list1.get(current1) < list2.get(current2)) {
temp.set((current3++), list1.get(current1++));
} else {
temp.set((current3++), list2.get(current2++));
}
}
while (current1 < list1.size()) {
temp.set((current3++), list1.get(current1++));
}
while (current2 < list2.size()) {
temp.set((current3++), list2.get(current2++));
}
return temp;
}
}
Among other things, you are returning
a, nottemp. As far as I can tell, you never modifya.Perhaps you are confused about what
List.subList()does. It returns a view of the list, so whatever you’re doing with it insort‘s penultimate statement will have no effect since you’re disregarding the return value.