Tim*_*ler 0 c# arrays 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);
}
Run Code Online (Sandbox Code Playgroud)
所以我搜索数组的中间,如果值大于我们寻找的值,我们搜索左半部分的中间,依此类推......
但即使它们在阵列中,它也找不到一些值.有人能看到错误吗?
你使用索引错了.
int currIndex = (rb - lb) / 2;
Run Code Online (Sandbox Code Playgroud)
你需要获得rb和lb的中间点,这将是:
int currIndex = lb + (rb - lb) / 2;
// or
// int currIndex = (lb + rb) / 2;
Run Code Online (Sandbox Code Playgroud)
如果值不存在,您还需要以某种方式退出递归,因为当前它将继续并导致堆栈溢出.你可以通过检查以确保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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2165 次 |
| 最近记录: |