[英]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.