ArrayList.BinarySearch returns various negative values if item not found

  • Thread starter Thread starter illegal.prime
  • Start date Start date
I

illegal.prime

So I see from the documentation here:
http://msdn.microsoft.com/library/d...ollectionsArrayListClassBinarySearchTopic.asp

That the code uses the less than operator:
int myIndex=myList.BinarySearch( myObject );
if ( myIndex < 0 )

when using the BinarySearch method and in my own experience I see that
sometimes it returns other negative values (other than -1).

What is the significance of the various negative values? I'm used to
methods that return indices to return only -1 on failure - do these
other negative values tell you how many times it had to divide and
conquer to reach the conclusion that the value doesn't occur in the
ArrayList?

Thanks,
Novice
 
So I see from the documentation here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
cpref/html/frlrfSystemCollectionsArrayListClassBinarySearchTopic.asp

That the code uses the less than operator:
int myIndex=myList.BinarySearch( myObject );
if ( myIndex < 0 )

when using the BinarySearch method and in my own experience I see that
sometimes it returns other negative values (other than -1).

What is the significance of the various negative values? I'm used to
methods that return indices to return only -1 on failure - do these
other negative values tell you how many times it had to divide and
conquer to reach the conclusion that the value doesn't occur in the
ArrayList?

From the first overload in the documentation you linked to:

<quote>
Return Value

The zero-based index of value in the sorted ArrayList, if value is
found; otherwise, a negative number, which is the bitwise complement of
the index of the next element that is larger than value or, if there is
no larger element, the bitwise complement of Count.
</quote>

and

<quote>
If the ArrayList does not contain the specified value, the method
returns a negative integer. You can apply the bitwise complement
operation (~) to this negative integer to get the index of the first
element that is larger than the search value. When inserting the value
into the ArrayList, this index should be used as the insertion point to
maintain the sort order.
</quote>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top