简体   繁体   English

使用递归在数组中查找值

[英]Find value in array with recursion

I am trying to find a value in an array with a specific method. 我正在尝试使用特定方法在数组中查找值。

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

So I search the middle of the array, if the value is bigger than the value we look for, we search the middle of the left half and so on... 所以我搜索数组的中间部分,如果该值大于我们寻找的值,我们搜索左半部分的中间,依此类推...

But it doesnt find some values even if they are in the array. 但是,即使它们在数组中,也不会找到某些值。 Can someone see a mistake? 有人可以看到一个错误吗?

You're using the index wrong. 您使用的索引错误。

int currIndex = (rb - lb) / 2;

You need to get the middle point of rb and lb which would be: 您需要获取rb和lb的中间点,即:

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

You will also need an exit out of the recursion somehow if the value isn't present because currently it will just go on and cause a stack overflow. 如果不存在该值,则还需要以某种方式退出递归,因为当前该值将继续存在并导致堆栈溢出。 You could do that by checking to ensure lb and rb are different for example: 您可以通过检查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);
    }   
}
int currIndex = (rb - lb) / 2;

should be 应该

int currIndex = (rb + lb) / 2;

You need to find a midpoint. 您需要找到一个中点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM