The output of this code is always the last digit of the input. Cannot find the reason.I use merge sort recursively, and the result is wrong. I thought maybe the list being overlapped.
public class MergeSort {
public static List<Integer> Sort(List<Integer> list) {
if (list.size() <= 1) {
return list;
}
List<Integer> aList = new ArrayList<Integer>();
aList = list.subList(0, list.size() / 2);
List<Integer> bList = new ArrayList<Integer>();
bList = list.subList(list.size() / 2, list.size());
Sort(aList);
Sort(bList);
merge(aList, bList, list);
return list;
}
private static List<Integer> merge(List<Integer> alist,
List<Integer> blist, List<Integer> list) {
int alistIndex = 0, blistIndex = 0, listIndex = 0;
while (alistIndex < alist.size() && blistIndex < blist.size()) {
if (alist.get(alistIndex) < blist.get(blistIndex)) {
list.set(listIndex, alist.get(alistIndex));
alistIndex++;
} else {
list.set(listIndex, blist.get(blistIndex));
blistIndex++;
}
listIndex++;
}
List<Integer> rest;
if (alistIndex == alist.size()) {
rest = blist.subList(blistIndex, blist.size());
for(int c = blistIndex; c < rest.size(); c++){
list.set(listIndex, blist.get(c));
listIndex++;
}
} else {
rest = alist.subList(alistIndex, alist.size());
for(int c = alistIndex; c < rest.size(); c++){
list.set(listIndex, alist.get(c));
listIndex++;
}
}
return list;
}
}
The test input is 5, 4, 3, 2, 1. But the output is 1, 1, 1, 1, 1. So, there must have some wrong with this merge method
The quick fix to your problem is replacing:
with:
You create new
ArrayList
s for your partitions then immediately change the reference to a view of your original list.The partitioning of the list is being done correctly, however, because you are using the view instead of the shallow copies, during the merge you are changing your partitions.
Usually if you are doing a sort that mutates the original list, you don't return anything from that method, so something like:
The alternative where the original list isn't mutated could be: