I have a java code of mergesort for ArrayList but it doesn't sort correctly the ArrayList. But I don't find the mistake.
The code is:
public void mergeSort(ArrayList<Integer> list, int beg, int fin) {
if (beg < fin) {
int mid= (beg + fin) / 2;
mergeSort(list, beg, mid);
mergeSort(list, mid + 1, fin);
Merge(list, beg, mid, fin);
}
}
public void Merge(ArrayList<Integer> list, int beg, int mid, int fin) {
ArrayList<Integer> left = new ArrayList<>(list.subList(beg, mid));
ArrayList<Integer> right = new ArrayList<>(list.subList(mid, fin));
int i = 0;
int j = 0;
int k = beg;
while (i < left.size() && j < right.size()) {
if (left.get(i) <= right.get(i)) {
list.set(k, left.get(i));
i++;
} else {
list.set(k, right.get(j));
j++;
}
k++;
}
while (i < left.size()) {
list.set(k, left.get(i));
i++;
k++;
}
while (j < right.size()) {
try {
list.set(k, right.get(j));
j++;
k++;
}
}
}
When I call it from other class...
jpanel4.mergeSort(jpanel4.lista, 0, jpanel4.lista.size() - 1);
(Merge is in jpanel4 class).
I converted a mergesort code for arrays to that, because it will work fine with other code that I have.
Thanks.