I have a problem with implementing a merge sort algorithm in Java: I've done merge sort algorithm but it couldn't produce the right result. I also return the sorted list from the function. How can I also do it?
Here is my merge sort algorithm defined below.
mergeSort method:
public static void mergeSort(ArrayList<Person> personList, Comparator<Person> compTr) {
ArrayList<Person> helper = new ArrayList<Person>();
mergeSort(personList, helper, 0, personList.size() - 1, compTr);
}
mergeSort function:
private static void mergeSort(ArrayList<Person> list,
ArrayList<Person> helper,
int low,
int high,
Comparator<Person> compTr) {
if (low < high) {
int middle = (low + high) / 2;
mergeSort(list, helper, low, middle, compTr); //sort left half
mergeSort(list, helper, middle + 1, high, compTr); //sort right half
merge(list, helper, low, middle, high, compTr); // merge
}
}
merge algorithm:
private static void merge(ArrayList<Person> list,
ArrayList<Person> helper,
int low,
int middle,
int high,
Comparator<Person> compTr) {
//This loop throws Exception
for (int i = low; i < high + 1; i++) {
helper.add(i, list.get(i));
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
while (helperLeft < middle && helperRight < high) {
if (isGreaterThan(helper.get(helperLeft), helper.get(helperRight), compTr)) {
list.set(current, helper.get(helperLeft));
helperLeft++;
} else {
list.set(current, helper.get(helperRight));
helperRight++;
}
current++;
}
//Copy remaining elements
int remaining = middle - helperLeft;
for (int j = 0; j <= remaining; j++) {
list.set(current + j, helper.get(helperLeft + j));
}
// RETURN LIST(list) _-> TO DO
}
Implement Comparator feature
public static boolean isGreaterThan(Person helperLeft, Person helperRight, Comparator<Person> compTr) {
return greaterThan(compTr, helperLeft, helperRight);
}
private static boolean greaterThan(Comparator comp, Person x, Person y) {
return comp.compare(x, y) > 0;
}
How can I do this?