使用递归在数组中查找值

时间:2013-04-10 09:54:38

标签: 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);
        }   

所以我搜索数组的中间,如果值大于我们查找的值,我们搜索左半部分的中间等等......

但即使它们在数组中,它也找不到一些值。有人可以看到错误吗?

2 个答案:

答案 0 :(得分:6)

您使用的索引错误。

int currIndex = (rb - lb) / 2;

你需要获得rb和lb的中间点:

int currIndex = lb + (rb - lb) / 2;
// or
// int currIndex = (lb + rb) / 2;

如果值不存在,您还需要以某种方式退出递归,因为当前它将继续并导致堆栈溢出。您可以通过检查来确保lbrb不同,例如:

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);
    }   
}

答案 1 :(得分:0)

int currIndex = (rb - lb) / 2;

应该是

int currIndex = (rb + lb) / 2;

你需要找到一个中点。