今天是个好日子!我这里有一个程序,它使用归并排序从文件中对 50,000 个单词进行排序。我在他的算法简介中遵循了 Thomas Cormen 的伪代码,当我手动“调试”它时似乎是正确的。但是,当我运行程序时,它会显示 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
. 是的,我认为这是由于大 NO_OF_WORDS
(即 50,000),但即使我将其减少到 10,它仍然显示相同的错误。
import java.io.*;
import java.util.*;
public class SortingAnalysis {
public static void merge(String[] A, int p, int q, int r) {
int n1 = q-p+1;
int n2 = r-q;
String[] L = new String[n1+1];
String[] R = new String[n2+1];
for (int i=1; i<n1; i++) {
L[i] = A[p+i-1];
}
for (int j=1; j<n2; j++) {
R[j] = A[q+j];
}
L[n1+1] = "zzzzz"; //for infinity because if I use Math.floor, it will return a double
R[n2+1] = "zzzzz";
int i=1;
int j=1;
for (int k=p; k<=r; k++) {
int comparison = L[i].compareTo(R[j]);
if (comparison <= 0){
A[k] = L[i];
i++;
}
else {
A[k] = R[j];
j++;
}
}
}
public static void mergeSort (String[] A, int p, int r) {
if (p<r) {
int q = (p+r)/2;
mergeSort(A, p, q);
mergeSort(A, q+1, r);
merge(A, p, q, r);
}
}
public static void main(String[] args) {
final int NO_OF_WORDS = 50000;
try {
Scanner file = new Scanner(new File(args[0]));
String[] words = new String[NO_OF_WORDS];
int i = 0;
while(file.hasNext() && i < NO_OF_WORDS) {
words[i] = file.next();
i++;
}
long start = System.currentTimeMillis();
mergeSort(words, 0, words.length-1);
long end = System.currentTimeMillis();
System.out.println("Sorted Words: ");
for(int j = 0; j < words.length; j++) {
System.out.println(words[j]);
}
System.out.print("Running time: " + (end - start) + "ms");
}
catch(SecurityException securityException) {
System.err.println("Error");
System.exit(1);
}
catch(FileNotFoundException fileNotFoundException) {
System.err.println("Error");
System.exit(1);
}
}
}
我认为这是因为 String[] L 和 R 的声明。或者不是。请帮我看看有什么问题。非常感谢!
编辑
Cormen 的伪代码
MERGE(A, p, q, r )
n1 ← q − p + 1
n2 ←r − q
create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
for i ← 1 to n1
do L[i ] ← A[p + i − 1]
for j ← 1 to n2
do R[ j ] ← A[q + j ]
L[n1 + 1]←∞
R[n2 + 1]←∞
i ← 1
j ← 1
for k ← p to r
do if L[i ] ≤ R[ j ]
then A[k] ← L[i ]
i ←i + 1
else A[k] ← R[ j ]
j ← j + 1