Search code examples
javarecursionstack-overflowlinear-search

Getting stack overflow error when running recursive linear search


I realize that a binary search would be much more efficient and I even have one working but I'm required to write a recursive linear search for a lab. i keep getting stack overflow on the method linSearch(), specifically on line 33.

I'm required to search arrays as big as 1,280,000.

import java.util.Scanner;
public class linSearch {    
    public static void main(String[] args){
       Scanner in = new Scanner(System.in);
       System.out.println("enter size");
       int size = in.nextInt();
       System.out.println("enter numb");
       double numb = in.nextDouble();
       double [] array = new double[size];
       for(int i = 0; i < 30; i++){
          for(int j = 0; j < size-1; j++){
              double random = (int)(Math.random() * 1000000);
              array[j] = (double)(random / 100);
          }
          int position = linSearch(array, numb, 0);
          if(position == -1){
              System.out.println("the term was not found");
         }
        else{
            System.out.println("the term was found");
        }
    }
}
public static int linSearch(double[] array, double key, int counter){
    if(counter == array.length){
        return -1;
    }
        if(array[counter] == key){
            return counter;
        }
        else{
            counter += 1;
            return linSearch(array, key, counter);  //error occurs here
        }
    }
}

Solution

  • You'd be lucky if your stack could hold 15000 interative call to itself never mind 128,000 However If you have verified that the recursion is implemented correctly, you can increase the stack’s size, in order to allow a larger number of invocations. Depending on the Java Virtual Machine (JVM) installed, the default thread stack size may equal to either 512KB, or 1MB.

    However You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line.

    Click & Follow Guide Here

    Hope this helps