Hi All,
I'm am new to C and was working on a binary search algorithm.
The last else in the while loop has a statement wrapped in curly brackets and it compiles without errors given. But when i run the code it enters an infinite loop. When i remove the curly brackets it gives no errors and runs fine. I don't understand why it gets stuck in an infinite loop. Why is that? Any C experts maybe wanna explain more about this please?
This is the piece of code:
Code:
bool search(int value, int values[], int n)
{
int first = 0;
int last = n - 1;
int middle = ( first + last ) / 2;
while ( first <= last )
{
if ( values[middle] == value )
{
return true;
}
else if ( values[middle] < value )
{
first = middle + 1;
}
else
{
last = middle - 1;
middle = ( first + last ) / 2;
} // when removing these bolded brackets the code runs fine
}
return false;
}
And for those interested in the piece of sorting code the above algorithm is merged with:
Code:
void sort(int values[], int n)
{
for ( int j = 0; j < n - i - 1; j++)
{
if ( values[j] > values[j+1] )
{
int swap = values[j];
values[j] = values[j+1];
values[j+1] = swap;
}
}
}
return;
}