I have the following binary search algorithmn:
int search_binary(int* tab,int size, int a)
{
int lower=0,upper=size-1,middle=(lower + upper)/2;
while(lower < upper)
{
if(tab[middle] == a)
break;
else if(tab[middle] < a)
{
upper = middle - 1;
middle = (lower + upper)/2;
} else {
lower = middle + 1;
middle = (lower + upper)/2;
}
}
if(tab[middle] == a)
return middle;
else
return -1;
}
It either return -1 if I insert a number, that exists or it returns the wrong index.
exampledata:
table: 2 2 4 5 7 7 8 8 8 9
searched number: 7
result: The index is: 4
table: 1 2 3 4 6 6 6 7 8 9
searched number: 4
result: The index is: -1
else if(tab[middle] < a)
{
upper = middle - 1;
middle = (lower + upper)/2;
}
From here it seems that you expect the array to be ordered in decreasing order. In fact, giving it an array ordered that way, it works for me.
just change the if
to:
if(tab[middle] > a)
To have it working for an array ordered in increasing order
A slight change in you loop in function -
int search_binary(int* tab,int size, int a)
{
int lower=0,upper=size-1,middle=(lower + upper)/2;
while(lower < upper)
{
if(tab[middle] == a){ // if found
return middle; // return index
}
else if(tab[middle] < a) // if a is greater
{
lower= middle ; //lower is updated to middle,search in part above middle
middle = (lower + upper)/2;
} else {
upper = middle - 1; //else upper is updated search in part lower than middle
middle = (lower + upper)/2;
}
}
return -1;
}
What mistake your loop was doing that when tab[middle]<a
then due to updation of upper
it would search number in part 0 to middle -1
whereas , number was at higher index.I have updated your code with correct changes in vairables.
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.