有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java二进制搜索基础。陷入无限循环

我正在尝试实现一种基本形式的二进制搜索。我创建了一个数组,并用线性值填充。现在只是想通过排序找到一个数字和它的索引。。问题是,它陷入了一个恒定的循环,并返回零。它会通过嵌套循环,因为它会打印,但无法找到目标值。下面是代码

for (int i= 1; i < 10000 ; i++){
        studentID[i] = i;
    }
   Students studentIDNumber = new Students();
   studentIDNumber.binarySearch(studentID, 400);


public void binarySearch(int[] studentID, int targetID){
    System.out.println("helloworld");
    int position = -1;
    int suspect;
    int suspectIndex = 0;
    int lastSuspectIndex = studentID.length-1;
    while(position == -1)
    {
        assert(suspectIndex<lastSuspectIndex);
        suspectIndex = ((studentID.length-1)/2);
        lastSuspectIndex =suspectIndex;
        suspect=studentID[suspectIndex];
        System.out.println(suspect);
        if(suspect == targetID){
            position = suspectIndex;
            System.out.println(suspectIndex +" is where the ID #"+targetID+" is sotred");
            break;
        }
         if(suspect < targetID){
            suspectIndex= suspectIndex+(suspectIndex/2); 
             position = -1;
            }
         if(suspect > targetID){
            suspectIndex= suspectIndex-(suspectIndex/2); 
            position = -1;}
        else {
            System.out.println("ID not found " );   
            }
    }

 }

共 (1) 个答案

  1. # 1 楼答案

    在这一行:

      suspectIndex = ((studentID.length-1)/2);
    

    每个循环迭代的怀疑指数都是相同的。在循环之前初始化变量一次,但不要在循环开始时初始化