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

时间:2015-09-21 04:52:23

标签: java sorting search binary

我试图实现二进制搜索的基本形式。我创建了一个数组并填充了线性值。现在只是尝试对它进行排序以找到一个数字及其索引。问题是它被卡在一个常量循环中并返回零。它通过嵌套循环,因为它打印但无法找到目标值。以下是代码

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 个答案:

答案 0 :(得分:3)

在这一行:

  suspectIndex = ((studentID.length-1)/2);
对于每次循环迭代,

suspectIndex都是相同的。在循环之前初始化变量一次,但不在循环开始时初始化。