Bit Flipping the Binary Search Result

When I did the Atlas hands on lab weeks ago, the following piece of code jumped out at me:

int index = Array.BinarySearch(

       autoCompleteWordList,

       prefixText,

       new CaseInsensitiveComparer()

   );

 

if (index < 0)

{

    index = ~index;

}

Why is the code doing a bitwise complement (~) on the return value of BinarySearch?

My next stop was the documentation for the return value of Array.BinarySearch, which states:

The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value

In other words, if you don’t find an exact match you can flip all the bits and have an index pointing to something close – a good trick to know when building an auto-complete control.

Print | posted @ Sunday, October 09, 2005 3:40 AM

Comments on this entry:

Gravatar # re: Bit Flipping the Binary Search Result
by Milan Negovan at 10/10/2005 2:16 PM

What documentation misses is a hint that the array should be sorted first. Otherwise the bit complement might not give you an accurate position index. I've been bitten by this before.
  
Gravatar # re: Bit Flipping the Binary Search Result
by Scott Mitchell at 10/14/2005 5:06 AM

Milan, if you don't have a sorted array, BinarySearch is not going to work (unless you're lucky), let alone be able to have it's bit complement return a 'close estimate.'
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 1 and 7 and type the answer here: