0

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?

  • The mistake is that having 100K recursive calls of `selectionSort` method with three arguments is too much for JVM. If you have not tweaked the stack size setting before running this code, by default, the stack size per thread is just 512K – Nowhere Man Mar 01 '22 at 17:39

1 Answers1

0

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?

pringi
  • 3,987
  • 5
  • 35
  • 45