dimanche 29 mars 2015

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
}
}
}



Aucun commentaire:

Enregistrer un commentaire