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