简体   繁体   中英

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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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