【发布时间】:2015-03-30 02:49:00
【问题描述】:
我意识到二进制搜索会更有效,我什至有一个工作,但我需要为实验室编写递归线性搜索。
我一直在方法 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,280,000 个堆栈帧。您需要编写算法的迭代版本或实现二进制搜索。二进制搜索只需要堆栈 log2(1280000) = 20 帧深。
-
线性搜索不适合递归解决方案。如果它需要处理像您所说的那样大的输入,您不太可能以这种方式编写工作程序。改为执行迭代线性搜索。
-
感谢您的回复,但问题是这个实验室需要递归线性搜索,我无法解决这个问题
-
好吧,除了需要有序输入的二进制搜索...请注意,许多非更新递归算法(例如搜索)可以稍微并行化。我会假设在获得
n的帧数之后,它会以分而治之的方式变为非递归版本(我感觉这就是@axblount 的真正意思)。您只能并行化大约2x + 1任务(其中x是可用处理器的数量),所以要深入,或者直到有8 个元素要搜索。哦,你可能会发现把 main 方法分解一下也是值得的。 -
@Clockwork-Muse 我认为他应该只使用一个危险的 for 循环。
标签: java recursion stack-overflow linear-search