This is my code:
int Binary (int* arr, unsigned int size, int num)
{
if (0 == size)
{
return -1;
}
if (1 == size)
{
if (arr[0] == num)
{
return 0;
}
return -1;
}
size/= 2;
if (num == arr[size])
{
return size;
}
else
{
if (num < arr[size])
{
Binary (arr, size, num);
}
else
{
Binary (&arr[size+1], size, num);
}
}
return -1;
}
It doesn't work. When I debug it (trying to search a number that appears in an array), I see that it goes into the line of 'return size', which it should do (side question- is there a way to put line numbers in the code..) but then it keeps going to the last line and returns -1. How come I have a return and it doesn't go out of the function? I first tried not to put any return in the end because I am not supposed to reach to the end, but the compiler says "control reaches end of non-void function" so I added the last return, but obviously it is not the right thing to do..
Thanks
You should return the results of the recursive call
int Binary (int* arr, unsigned int size, int num)
{
if (0 == size)
{
return -1;
}
if (1 == size)
{
if (arr[0] == num)
{
return 0;
}
return -1;
}
size/= 2;
if (num == arr[size])
{
return size;
}
else
{
if (num < arr[size])
{
return Binary (arr, size, num); // Added return
}
else
{
return Binary (&arr[size+1], size, num); // Added return
}
}
}