0

我意识到二进制搜索会更有效,我什至有一个工作,但我需要为实验室编写递归线性搜索。我一直在方法上出现堆栈溢出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
        }
    }
}
4

1 回答 1

0

如果您的堆栈可以容纳 15000 次对自身的交互调用,那您会很幸运,更不用说 128,000。但是,如果您已验证递归已正确实现,则可以增加堆栈的大小,以允许更多的调用。根据安装的 Java 虚拟机 (JVM),默认线程堆栈大小可能等于 512KB 或 1MB。

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

单击并在此处遵循指南

希望这可以帮助

于 2015-03-30T03:31:36.430 回答