I am trying to implement a mergeSort function to sort an ArrayList of words that I got from input.txt. (I use the DeleteStopWords() method for this.
The sorted ArrayList that is being returned does not sort properly however I cannot understand why.
Below are my mergSort and merge methods.
public static ArrayList<String> mergeSort(ArrayList<String> listofWords) {
ArrayList<String> sorted = new ArrayList<String> ();
if (listofWords.size() == 1) {
sorted = listofWords;
} else {
int middle = listofWords.size() / 2;
ArrayList<String> leftSide = new ArrayList<String> ();
ArrayList<String> rightSide = new ArrayList<String> ();
for (int x = 0; x<middle; x++) {
leftSide.add(listofWords.get(x));
}
for (int x = 0; x<middle; x++) {
rightSide.add(listofWords.get(x));
}
mergeSort(leftSide);
mergeSort(rightSide);
sorted = merge(leftSide, rightSide);
}
return sorted;
}
public static ArrayList<String> merge(ArrayList<String> leftSide, ArrayList<String> rightSide) {
ArrayList<String> Sortedarray = new ArrayList<String> ();
int index = 0;
int leftIndex = 0;
int rightIndex = 0;
while (leftIndex<leftSide.size() && rightIndex<rightSide.size()) {
if ((leftSide.get(leftIndex)).compareTo(rightSide.get(rightIndex))<0) {
Sortedarray.add(leftSide.get(leftIndex));
leftIndex++;
} else {
Sortedarray.add(rightSide.get(rightIndex));
rightIndex++;
}
index++;
}
while (leftIndex<leftSide.size()) {
Sortedarray.add(leftSide.get(leftIndex));
leftIndex++;
index++;
}
while (rightIndex<rightSide.size()) {
Sortedarray.add(rightSide.get(rightIndex));
rightIndex++;
index++;
}
return Sortedarray;
}
mergeSortmethod is returning the sorted result in a different list. When calling recursively, you are ignoring the returned partial result. The problem is here:mergeSort(leftSide);and in the following line. I trust you to fix it yourself.