I am currently trying to implement a Merge Sort algorithm in Java based on the one found in Introduction to Algorithms: Third Edition.
The authors use a divide and conquer algorithm that also implements sentinel cards (here is pseudo code). These cards are supposed to have a value of infinity, but since I am using an array of strings, I assumed that the value would be null
. Apparently that is not the case because when I try comparing L[i] and R[j] I get a Null Pointer Exception. Here is my code:
public static void main(String[] args) {
Scanner textfile = new Scanner(System.in);
System.out.println("Enter a filename: ");
String fileName = textfile.nextLine();
String[] words = readArray(fileName);
mergeSort(words, 0, words.length - 1);
for (String word : words) {
System.out.println(word);
}
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for(int i = 0; i < ctr; i++) {
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e){
System.out.println("File not found.");
}
return null;
}
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 merge(String[] A, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
String[] left = new String[n1 + 1];
String[] right = new String[n2 + 1];
for (int i = 0; i < n1; i++) {
left[i] = A[p + i];
}
for (int j = 0; j < n2; j++) {
left[j] = A[q + j + 1];
}
left[n1] = null;
right[n2] = null;
for (int i = 0, j = 0, k = p; k < r; k++) {
if (left[i].compareTo(right[j]) <= 0) { \\Null Pointer Exception
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
}
So what's the problem? Is it because I declared the two arrays as null
? I tried things like "zzzz" and still get the same problem. Or am I completely missing something else?
Also, the pseudo code assumes that the array starts at index 1, which is why there are slight changes in my code. Did I do something wrong there?