【问题标题】:Binary search basic . Stuck in an Infinite loop二分搜索基本。陷入无限循环
【发布时间】:2015-12-17 16:52:17
【问题描述】:

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

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 " );   
            }
    }

 }

【问题讨论】:

  • 您的问题始于语句 lastSuspectIndex =suspectIndex; 1,2,3,4,5,6,7 现在空运行代码,你会得到,如果 TargetID>SuspectID 它一定是suspectId=SuspectId+(SuspectID/2);
  • 您正在将suspectIndex 重置为每个循环长度的一半。它每次都检查相同的位置,这就是它永远不会退出的原因。您应该将第一次初始化放在循环之外。不幸的是,代码中还有很多其他问题(例如,如果 suspectIndex 是 7500 并且太小,那么它将变为 7500 + 7500 / 2,然后超出范围)。

标签: java sorting search binary


【解决方案1】:

在这一行:

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

suspectIndex 对于每个循环迭代都是相同的。在循环之前初始化变量一次,但不在循环本身的开头。

【讨论】:

  • 是的,这是主要故障。虽然现在它只能找到奇数目标。我想看看是否可以修复!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多