当我运行它时,合并排序没有发生,我无法弄清楚问题出在哪里。存在 int brelem 和 SortThread 任务参数只是因为我需要它们正确地覆盖父类的方法,因此它们在这种情况下不起任何作用。
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;
}
}