我需要帮助将合并排序与字符串数组一起使用。我已经看到了很多使用 int 数组的示例,但我需要使用字符串数组的帮助。我只能使用 .compareTo() 方法。这是我的主要方法:
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);
}
这些是我的方法:
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 +" ");
}
当我运行程序时,它会正确地对其中的一些进行排序,但总的来说它不是无序的。