我的二进制搜索只能提供数组中前 4 个条目的值。对于每一个更大的值,程序都会卡住并自行关闭,除非我的值在数组的上半部分,然后它只是跳转到返回 -1 ...我真的找不到我的错误在这里
int BinarySearch(int data[], int numElements, int searchKey)
{
int mid;
int numMin = 0;
while (numMin <= numElements)
{
mid = numMin + floorf ((numElements - 1) / 2); // middle of the array initializing
//Searched Value is right at the middle
if (data[mid] == searchKey)
{
return mid;
}
// If Searched value is greater, ignore left half
else if (data[mid] < searchKey)
{
numMin = mid + 1; // new lowest value is middle of array +1
}
// If Searched value is smaller, ignore right half
else
{
numElements = mid - 1; // new highest value is middle of the array -1
}
}
return -1;
}
最佳答案
你对 numElements
的理解有误,你一开始用它作为元素的数量,但它应该是 endIndex
,而 numMin
应该是 startIndex
。
while 循环的第一行是错误的:
mid = numMin + floorf ((numElements - 1) / 2);
应该是:
mid = (numMin + numElements) / 2;
关于c++ - 我的二进制搜索程序简单地关闭了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910181/