运行递归线性搜索时出现堆栈溢出错误

时间:2015-03-30 02:49:00

标签: java recursion stack-overflow linear-search

我意识到二进制搜索会更有效率,我甚至有一个工作但我需要为实验室编写递归线性搜索。 我继续在方法linSearch()上获得堆栈溢出,特别是在第33行。

我需要搜索大到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
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果你的筹码可以保持15000次对话,你会很幸运,从不介意128,000 但是,如果您已验证正确实现了递归,则可以增加堆栈的大小,以允许更多的调用。根据安装的Java虚拟机(JVM),默认线程堆栈大小可能等于512KB或1MB。

但是您可以使用-Xss标志增加线程堆栈大小。可以通过项目配置或命令行指定此标志。

Click & Follow Guide Here

希望这有帮助