Getting StackOverflowError when using long data type while trying recursion. Tried type conversion where ever possible but I am unable to solve this error. Code:
import java.util.Arrays;
class Demo
{
// Utility function to swap values at two indices in the array
public static void swap(long[] arr, long i, long j)
{
long temp = arr[(int) i];
arr[(int) i] = arr[(int) j];
arr[(int) j] = temp;
}
// Recursive function to perform selection sort on subarray `arr[i…n-1]`
public static void selectionSort(long[] arr, long i, long n)
{
// find the minimum element in the unsorted subarray `[i…n-1]`
// and swap it with `arr[i]`
long min = i;
for (long j = i + 1; j < n; j++)
{
// if `arr[j]` is less, then it is the new minimum
if (arr[(int) j] < arr[(int) min]) {
min = j; // update the index of minimum element
}
}
// swap the minimum element in subarray `arr[i…n-1]` with `arr[i]`
swap(arr, min, i);
if (i + 1 < n) {
selectionSort(arr, i + 1, n);
}
}
public static void main(String[] args)
{
long[] arr = new long[100000];
Arrays.setAll(arr, i -> i + 1);
selectionSort(arr, 0, arr.length);
// print the sorted array
for (long i = 0; i< arr.length; i++)
System.out.print(arr[(int) i] + " ");
System.out.print("\n");
}
}
This is the error i am getting when i try to run the code.
Exception in thread "main" java.lang.StackOverflowError
at Demo.selectionSort(Demo.java:28)
at Demo.selectionSort(Demo.java:31)
at Demo.selectionSort(Demo.java:31)
at Demo.selectionSort(Demo.java:31)
What mistake am i doing?