I need help with using merge sort with a string array. I’ve seen many examples of this with an int array but I need help using a string array. I can only use the .compareTo() method. This is my main method:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] nameList = {"John", "Mark", "Amber", "Tony", "Matt", "George",
"Will", "Bob", "Paul", "Mary Ellen", "Kate", "Joe", "Fred", "Joe",
"Anne", "Amber", "Kimberly", "Kelsey", "Matthew"};
//print original
System.out.println("Before sorting the names: ");
for(String element: nameList)
System.out.print(element + " ");
System.out.println("\n");
//Merge Sort
System.out.println("After sorting the names: ");
mergesort(nameList, 0, nameList.length);
}
These are my methods:
private static void merge(String[] data, int first, int n1, int n2) {
String[] temp = new String[n1 + n2];
int copied = 0;
int copied1 = 0;
int copied2 = 0;
while((copied1 < n1) && (copied2 < n2)) {
if(data[first + copied].compareTo(data[first + n1 + copied2]) < 0)
temp[copied++] = data[first + (copied1++)];
else
temp[copied++] = data[first + n1 +(copied2++)];
}
while(copied1 < n1)
temp[copied++] = data[first + (copied1++)];
for(int i = 0; i < copied; i++)
data[first +i] = temp[i];
}
public static void mergesort(String[] data, int first, int n) {
int n1 = 0;
int n2 = 0;
if(n > 1) {
n1 = n/2;
n2 = n-n1;
mergesort(data, first, n1);
mergesort(data, first + n1, n2);
}
merge(data, first, n1, n2);
for(String element: data)
System.out.print(element +" ");
}
When I run the program it sorts some of it correctly but over all it is not inorder.
You have one typo and two forgotten lines. Below is fixed function. Compare it with your one.