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