This is my java code.
public static int[] merge_sort(int[] arr, int p, int r) {
if (p < r) {
int q = p + r / 2;
merge_sort(arr, p, q);
merge_sort(arr, q + 1, r);
merge(arr, p, q, r);
}
return arr;
}
public static void merge(int[] arr, int p, int q, int r) {
int i = p;
int j = q + 1;
int[] tempArr = new int[arr.length];
System.out.println(tempArr.length);
int k = p;
while (i <= q && j <= r) {
if (arr[i] <= arr[j]) {
tempArr[k] = arr[i];
i++;
} else {
tempArr[k] = arr[j];
j++;
}
k++;
}
while (i <= q) {
tempArr[k] = arr[i];
i++;
k++;
}
while (j <= r) {
tempArr[k] = arr[j];
j++;
k++;
}
for (int h = p; h <= r; h++) {
arr[h] = tempArr[h];
}
}
And my test code is here.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] testArr = {3, 5, 1, 9, 2};
int[] sortedArr = merge_sort(testArr, 0, testArr.length - 1);
for (int num: sortedArr) {
System.out.print(num);
}
}
When I tested with my test code, 'java.lang.StackOverflowError' error was called. Error is occurred in 'merge_sort(arr, p, q);' line. I don't know why this error occurred. What's wrong with my code?