'Stackoverflow Error while using long datatype

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?



Solution 1:[1]

You hit the "maximum recursion call depth"/maximum stack size in Java.

You can solve this exact problem with the -Xss20m parameter when running your program.

References: Set maximum recursion depth in java, Why is the max recursion depth I can reach non-deterministic?, JVM option -Xss - What does it do exactly?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pringi