Loops 使用While循环的二进制搜索(无限)
我必须使用循环(while)实现一个二进制搜索方法。出于某种奇怪的原因(嗯,对我来说很奇怪),循环一直在无限地进行,即使满足了退出循环的某些条件。我做错了什么Loops 使用While循环的二进制搜索(无限),loops,search,while-loop,binary,Loops,Search,While Loop,Binary,我必须使用循环(while)实现一个二进制搜索方法。出于某种奇怪的原因(嗯,对我来说很奇怪),循环一直在无限地进行,即使满足了退出循环的某些条件。我做错了什么 public void Bin_search(ArrayList<Integer> arrayList, int targetValue) { int totalCount = 0; int low = 0; int high = arrayList.size(); while (low <= high)
public void Bin_search(ArrayList<Integer> arrayList, int targetValue)
{
int totalCount = 0;
int low = 0;
int high = arrayList.size();
while (low <= high)
{
int mid = low + (high - low) / 2;
if(targetValue < arrayList.get(mid))
high = mid - 1;
else if(targetValue > arrayList.get(mid))
low = mid + 1;
else
totalCount++;
}
System.out.println("Number of times "+targetValue+" appears: "+totalCount+" time(s).");
}
public void Bin_搜索(ArrayList ArrayList,int targetValue)
{
int totalCount=0;
int低=0;
int high=arrayList.size();
while(低arrayList.get(中))
低=中+1;
其他的
totalCount++;
}
System.out.println(“出现次数”+targetValue+“+totalCount+”时间”);
}
问题在于您的算法。我敢肯定,二进制搜索假设列表是唯一且有序的,并且在找到值时返回/转义循环,或者通过更改最小/最大值在列表中迭代。在找到值的最后一个else中,它所做的只是递增计数器,它永远不会返回(正常的二进制搜索将跳出循环),也不会更新最小值或最大值,因此在未来的循环中,您的猜测总是相同的。它总是会找到它,并且总是递增,但永远不会转义,这就是为什么如果找到值,它是一个无限循环,但是如果找不到值,它将转义循环。调试器说了什么?什么条件没有得到正确处理?调试器什么也没说-一切都编译得很好,但当我运行它,传递参数并调用方法时,程序陷入了无限循环中。这时,你可以用调试器一步一步地检查它,看看出了什么问题。好的。所以我试着重写代码,这次我使用了return语句而不是void。奇怪的是,它起了作用。这可能与totalCount
有关吗?