I'm trying to use merge sort to alphabetically sort a list of words inputted from the command prompt. It works when I sort an arraylists up to a size of 4 words, but when I try using five or more words: it returns the array in the wrong order or in the same order it originally was in.
When I debugged it I realized that it sorts correctly all the way up until it comes to merging the last two halves. Ex. if its an arraylist of size 7, it sorts correctly the words in positions 0 - 4 and the words in positions 5 - 7 but merges them in the wrong order.
Due to this, I believe the error is in the mergeSort function, since the merge function is working considering it was able to sort the smaller arrays correctly. However, I don't see how there can be an error there since it just divides the array in half and calls other functions.
Comparing it to other mergesort functions I found online and on here, the code is very similar so I'm having a hard time seeing my mistake.
The inputting words from the cmd and calling mergesort is below:
public static void main(String[] args) {
List<String> List = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(input.hasNextLine()){
String word = input.nextLine().trim();
if (word.equals("")) break;
List.add(word);
}
input.close();
System.out.println("unsorted: " + ListA);
mergeSort(List, 0, List.size()-1);
System.out.println("sorted: " + ListA);
}
My mergeSort function and merge function are these:
public static void mergeSort(List<String> wordArray, int lower, int upper) {
if ((upper-lower) >= 1 ) {//if arraylist size is greater than 1
int halfPt = (upper + lower)/2; //dividing the arraylist
int s1 = lower;
int f1 = halfPt;
int s2 = halfPt +1;
int f2 = upper;
mergeSort(wordArray, s1, f1); //mergesort on first half
mergeSort(wordArray, s2, f2); //mergesort on second half
merge(wordArray, s1, f1, s2, f2); //merge first and second half
}
}
public static void merge(List<String> wordArray, int s1, int f1, int s2, int f2) {
List<String> finalArray = new ArrayList<String>();
while (s1<=f1 && s2<=f2) { //alphabetically sorting both half arrays
if(wordArray.get(s1).compareTo(wordArray.get(s2))<0) {//placing smallest element first
finalArray.add(wordArray.get(s1));
s1++;
} else {
finalArray.add(wordArray.get(s2));
s2++;
}
}
//add leftovers in half-arraylists
while (s1 <= f1) {
finalArray.add(wordArray.get(s1));
s1++;
}
while (s2 <= f2) {
finalArray.add(wordArray.get(s2));
s2++;
}
for (int i = 0; i < wordArray.size(); i++) { //copy sorted array into original array
if (wordArray.size()!=finalArray.size()) break;
wordArray.set(i, finalArray.get(i));
}
}
Where could I be going wrong? Any help is very much appreciated, and thank you in advance!