I'm sorry if this is posted elsewhere (I can't find anything, as my problem is rather specific), but I understand (or least in theory) what the error is; I am having trouble on how to fix it. The code is supposed to show how merge sort works; The code runs, but it never hits the function call "merge" (code below, I know it is bad practice to call in all in imports, but it isn't a major project, so I don't care; Maybe it is just the preview, but it is written import java.util.; and import java.security.;).
import java.util.*;
import java.security.*;
public class Merge {
public static void mergeSort(int[] data) {
sortArray(data, 0, data.length - 1);
}
private static void sortArray(int[] data, int low, int high) {
if ((high - low) >= 1) {
int m1 = low + high;
int m2 = m1 + 1;
System.out.printf("Split: %s\n", subarrayString(data, low, high));
System.out.printf(" %s\n", subarrayString(data, low, m1));
System.out.printf(" %s\n\n", subarrayString(data, m2, high));
sortArray(data, low, m1);
sortArray(data, m2, high);
merge(data, low, m1, m2, high);
}
}
public static void merge(int[] data, int l, int m1, int m2, int r) {
int lIndex = l, rIndex = r, cIndex = l, combined[] = new int[data.length];
System.out.printf("Merge: %s\n", subarrayString(data, l, m1));
System.out.printf(" %s\n", subarrayString(data, m1, r));
while (lIndex <= data[rIndex]) {
if (data[lIndex] <= data[rIndex])
combined[cIndex++] = data[lIndex++];
else
combined[cIndex++] = data[rIndex++];
}
if (lIndex == m2)
while (rIndex <= r) combined[cIndex++] = data[rIndex++];
else
while (lIndex <= m1) combined[cIndex++] = data[rIndex++];
}
private static String subarrayString(int[] data, int low, int high) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i < low; i++)
temp.append(" ");
for (int i = 0; i < high; i++)
temp.append(" " + data[i]);
return temp.toString();
}
public static void main2() {
SecureRandom gen = new SecureRandom();
int[] data = new int[10];
for (int i = 0; i < data.length; i++) data[i] = 10 + gen.nextInt(50);
System.out.printf("\nUnsorted Array:\n%s\n\n", Arrays.toString(data));
mergeSort(data);
System.out.printf("\nSorted Array:\n%s\n\n", Arrays.toString(data));
}
}
Let me know if you need the driver file. To restate, the problem is that it never reaches the merge function call and results in a Stack Overflow error.