I was practicing to write the code for binary search after watching its short, before starting on pset3.
The code that I wrote asks for the length of array, then sorts it and asks for the number to be searched for. the following code is working, if the number is there in the list, but not if it's not.
can anyone one explain why? following is the code where key
is the number to be searched for in the array data
of size length
:
int midpoint = (length - 1) / 2;
int min = 0;
int max = length - 1;
while(true)
{
if(data[midpoint] > key)
{
max = midpoint - 1;
midpoint =(min + max) / 2;
}
else if(data[midpoint] < key)
{
min = midpoint + 1;
midpoint = (min + max)/2;
}
else if(data[midpoint] == key)
{
printf("the number %i is in the list.\n", key);
break;
}
else
{
printf("The number is not in the list.\n");
break;
}
}