I did not consult any reference for this implementation, so I guess there are bugs lurking everywhere.
Constructive criticisms welcome. And yes, it is C-ish.
int BinarySearch(int data[], unsigned int elements, int key)
{
if(elements==0)
{
cerr << "Binary search not able to perform on 0 element array";
exit(-1);
}
unsigned int half_offset = elements<<31? (elements-1)/2 : elements/2; // truncation will happen anyway.
unsigned int current_index = elements<<31? (elements-1)/2 : elements/2; // Non portable bitwise ops.
while(half_offset!=0)
{
if(data[current_index]==key)
return current_index;
else if(data[current_index]<key)
{
current_index += half_offset<<31? (half_offset+1)/2 : half_offset/2;
}
else if(data[current_index]>key)
{
current_index -= half_offset<<31? (half_offset+1)/2 : half_offset/2;
}
half_offset /= 2; // Truncated to floor
}
if(data[current_index]==key)
return current_index;
}