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?
Binary Search.