BinarySearch Not Searching Through All Items

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have created my own comparer class using IComparer for use with
ArrayList.BinarySearch. My class seems to work with BinarySearch, but the
problem is that my ArrayList has three items in it and it seems that
BinarySearch only searches the first two items. So if I happen to be looking
for the last item in the ArrayList, BinarySearch returns that it's not there.

Any ideas?
David McCarter


=====================
David McCarter
www.vsdntips.com
 
dotNetDave said:
I have created my own comparer class using IComparer for use with
ArrayList.BinarySearch. My class seems to work with BinarySearch, but the
problem is that my ArrayList has three items in it and it seems that
BinarySearch only searches the first two items. So if I happen to be
looking
for the last item in the ArrayList, BinarySearch returns that it's not
there.

Any ideas?
David McCarter


=====================
David McCarter
www.vsdntips.com

How are the objects in your ArrayList ordered?
Please excuse me if I'm belaboring the obvious, but a binary search
algorithm will only work correctly if the collection to be searched has been
sorted. The symptoms you describe are typical of what happens if a binary
search algorithm is applied to unsorted data.
If you did not apply the ArrayList.Sort method before calling BinarySearch,
that could be your problem.
 
David,
My class seems to work with BinarySearch, but the
problem is that my ArrayList has three items in it and it seems that
BinarySearch only searches the first two items.

That's how binary search works, and is what makes it perform well.

So if I happen to be looking
for the last item in the ArrayList, BinarySearch returns that it's not there.

As long as the list is properly sorted and your comparer is returning
the correct results, it should work.



Mattias
 
Back
Top