In his book, "Writing Correct Programs," Bentley wrote that 90% of the computer experts could not write a completely correct binary search algorithm within 2 hours.
I tried it myself, and it was really hard to write it right the first time. The following two implementations are iterative and recursive versions of the code, two-point lookup ideas Many people know, but here is a detail to pay attention to the choice of boundaries.
int search (int array[],int n,int v)
{
int left,right,middle;
left = 0,right = n-1;
while (left <= right)
{
Middle = (left + right)/2;
if (Array[middle] > V)
{
right = middle-1;
}
else if (Array[middle] < v)
{
left = middle + 1;
}
Else
{
return middle;
}
}
return-1;
}
int search_recurse (int array[],int low,int High,int v)
{
int middle;
Middle = (low + high)/2;
if (Low < high)
{
if (Array[middle] > V)
{
Return Search_recurse (ARRAY,LOW,MIDDLE,V);
}
else if (Array[middle] < v)
{
Return Search_recurse (Array,middle + 1,high,v);
}
Else
{
return middle;
}
}
else if (low = = high)
{
if (array[middle] = = v)
{
return middle;
}
Else
{
return-1;
}
}
Else
{
return-1;
}
return-1;
}
int main ()
{
int array[] = {0,1,2,3,4,5,6,7,13,19};
int m = Search (array,sizeof (array)/sizeof (Array[0]), 13);
printf ("M =%d\n", m);
m = Search_recurse (array,0,sizeof (array)/sizeof (Array[0]), 13);
printf ("M =%d\n", m);
return 0;
}