[英]Find value in array with recursion
我正在尝试使用特定方法在数组中查找值。
public void findElement(int valueToFind)
{
FindElementInArray(valueToFind, 0, _array.Length - 1);
}
public void FindElementInArray(int value, int lb, int rb)
{
int currIndex = (rb - lb) / 2;
if (_array[currIndex] == value)
{
//Value found
Console.WriteLine("Value found");
return;
}
//If found value is smaller than searched value
else if (_array[currIndex] < value)
{
FindElementInArray(value, currIndex+1, rb);
}
//If found value is bigger than searched value
else
{
FindElementInArray(value, lb, currIndex - 1);
}
所以我搜索数组的中间部分,如果该值大于我们寻找的值,我们搜索左半部分的中间,依此类推...
但是,即使它们在数组中,也不会找到某些值。 有人可以看到一个错误吗?
您使用的索引错误。
int currIndex = (rb - lb) / 2;
您需要获取rb和lb的中间点,即:
int currIndex = lb + (rb - lb) / 2;
// or
// int currIndex = (lb + rb) / 2;
如果不存在该值,则还需要以某种方式退出递归,因为当前该值将继续存在并导致堆栈溢出。 您可以通过检查lb
和rb
是否不同来做到这一点,例如:
if (_array[currIndex] == value)
{
//Value found
Console.WriteLine("Value found");
return;
}
else if (lb != rb)
{
//If found value is smaller than searched value
else if (_array[currIndex] < value)
{
FindElementInArray(value, currIndex+1, rb);
}
//If found value is bigger than searched value
else
{
FindElementInArray(value, lb, currIndex - 1);
}
}
int currIndex = (rb - lb) / 2;
应该
int currIndex = (rb + lb) / 2;
您需要找到一个中点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.